vuex报错 Cannot destructure property ‘commit‘ of ‘undefined

在使用vuex中的模块是遇到了一个报错,这个报错的意思是解构一个未定义的对象时发生的。
经过排查发现是在另一个模块的actions中调用了当前模块actions中的方法,没有传任何值,所以无法结构出来commit方法

原代码

//user.js
actions: {  
   async initUserInfo ({commit,state}){
     if( !state.userInfo ){
       let res = await userinfo();
       commit('initState',res.data.data)
       GlobalMenu.actions.initMenuInfo() // 这里调用了GlobalMenu中的initMenuInfo方法
     }
   },
}

// GlobalMenu.js
actions: {  
  async initMenuInfo ( ){
    let res = await getMenu(user.state.currentRolePerm);
    let newMenu = noemalizeMenu(res.data.data)
    commit('initMenu',newMenu)
  } 
}  

找到原因后针对修改,把commit传过去即可
修改后

//user.js
actions: {  
   async initUserInfo ({commit,state}){
     if( !state.userInfo ){
       let res = await userinfo();
       commit('initState',res.data.data)
       GlobalMenu.actions.initMenuInfo(commit) // 把commit传过去
     }
   },
}

// GlobalMenu.js
actions: {  
  async initMenuInfo (commit){
    let res = await getMenu(user.state.currentRolePerm);
    let newMenu = noemalizeMenu(res.data.data)
    commit('initMenu',newMenu)
  } 
}  

另外,在排查过程中看到有人说导致这个错误的原因还有可能是未在main.js文件中挂载store
https://blog.csdn.net/weixin_44530406/article/details/89578503

你可能感兴趣的:(vue学习记录,javascript,开发语言,ecmascript)