Vue.js使用VueX时遇Uncaught TypeError: 无法读取undefined的state属性
解决VueX中"Cannot read properties of undefined (reading 'state')"错误
你的错误核心原因是**app.mount("#app")与app.use(store)的调用顺序错误**:Vue应用挂载后会立刻开始渲染组件,此时如果还未注册VueX store,组件内的this.$store就是undefined,自然无法读取state属性。
修改main.js代码
将app.use(store)移到app.mount("#app")之前,确保store先被注入到应用中:
import { createApp } from "vue"; import { store } from "./store.js"; import App from "./App.vue"; const app = createApp(App); app.use(store); // 先注册VueX store app.mount("#app"); // 再挂载应用
验证与补充
修改后,组件内的this.$store.state.count就能正常访问到store中的count值。如果想使用mapState辅助函数,取消对应注释即可:
import { mapState } from 'vuex' export default { // ... computed: { ...mapState({ count: (state) => state.count, }), }, };
内容的提问来源于stack exchange,提问作者Vinoth Kumar
相关产品推荐
相关产品推荐

