Vue报错解决[Vue warn]: Error in render: “TypeError: Cannot read property ‘state‘ of undefined“

报错

Vue2项目中报错:
[Vue warn]: Error in render: “TypeError: Cannot read property ‘state’ of undefined”
[Vue warn]: Error in mounted hook: “TypeError: Cannot read property ‘dispatch’ of undefined”

在这里插入图片描述

常见原因

这个错误提示通常出现在 Vue 组件中,它尝试读取 Vuex store 的 state 对象,但是该对象没有被定义。这可能是由以下几个原因引起的:

1.Vuex store 模块没有正确导入。可以在 Vue 组件中使用以下代码导入store:

import store from '@/store'

这假设 store.js 文件位于 src/store 目录中。如果store.js 文件位于其他目录中,请相应地更改导入路径。

2.组件没有正确连接到 Vuex store。可以在 Vue 组件中使用以下代码将组件连接到 Vuex store:

import {
    
     mapState } from 'vuex'

export default {
    
    
  computed: {
    
    
    ...mapState(['myState'])
  }
}

这里的 myState 是Vuex store 中定义的状态名称。如果组件中使用其他名称,请相应地更改代码。

3.Vuex store 中没有定义所需的状态。
如果 Vuex store 中没有定义尝试使用的状态,则会出现这个错误。可以在 store.js 文件中使用以下代码定义状态:

const state = {
    
    
  myState: null
}

解决方法

反复确认代码后,发现并没有上述问题。所以想着看一下是不是版本问题,打开package.json一看vuex是4版本的。
在这里插入图片描述
这就好解决了:
运行以下命令卸载 Vuex 4:

npm uninstall vuex

运行以下命令安装 Vuex 3:

npm install vuex@3

猜你喜欢

转载自blog.csdn.net/zag666/article/details/130349794