You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 15:07:45