使用mapState获取Vuex store值时报Cannot read properties of undefined错误如何解决
可能的原因和对应解决方法:
1. state初始值设置问题,异步赋值时机差导致
你在Devtools里看到的是state异步更新完成后的最终值,而报错发生在组件初始化阶段:
- 大概率是你在Vuex的state定义中,
currentGame的初始值为undefined,没有设置默认空对象 currentGame是异步请求接口返回后才完成赋值,组件mounted执行时请求还未返回,此时this.currentGame为undefined,读取id属性就会抛出对应错误- 你测试
this.$store.state.currentGame.id的时机是在异步请求完成之后,所以不会报错
解决方法:
给store中的currentGame设置初始空对象:
// store的state定义 state() { return { currentGame: {}, // 其余state项 } }
或者取值时加可选链兼容undefined的情况:
console.log("currentGame.id ="+ this.currentGame?.id)
2. 带命名空间的子模块映射写法错误
如果currentGame是定义在开启了namespaced: true的子模块中,数组形式的mapState默认只会匹配根store的state,找不到对应字段就会返回undefined。
解决方法:
mapState第一个参数传入对应子模块的名称:
computed: { // 假设存储currentGame的子模块名为game ...mapState('game', [ 'currentSpeler' ,'currentSpelerCard', 'currentGame' ]), }
你可以先在mounted中打印console.log(this.currentGame)确认值本身是否为undefined,就能快速定位具体问题。
内容的提问来源于stack exchange,提问作者M.Koops
相关产品推荐
相关产品推荐

