Vue3使用Pinia Store报错:Cannot read properties of undefined (reading 'counter')
解决Vue3中Pinia Store报错"Cannot read properties of undefined (reading 'counter')"
直接错误原因及修复
你的组件代码中存在错误调用:console.log(storeCounter.store.counter)。调用useCounterStore()返回的store实例会直接暴露state中的所有属性,不需要额外通过.store访问。这行代码试图访问不存在的store属性,进而导致读取counter时触发undefined报错。
修正后的组件script代码
<script setup> import { computed, ref } from "@vue/reactivity" import { useCounterStore } from "@/stores/counter" const storeCounter = useCounterStore() console.log(storeCounter) // 直接访问state属性即可 console.log(storeCounter.counter) </script>
全局配置检查
如果修正后仍报错,需确认项目入口文件中已正确挂载Pinia:
// main.js/main.ts import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' const app = createApp(App) const pinia = createPinia() app.use(pinia) // 必须将Pinia挂载到Vue实例 app.mount('#app')
响应式解构补充(可选)
如果需要解构state属性并保持响应式,需使用Pinia提供的storeToRefs工具:
import { storeToRefs } from 'pinia' const storeCounter = useCounterStore() // 解构后counter仍保持响应式 const { counter } = storeToRefs(storeCounter)
内容的提问来源于stack exchange,提问作者Vlad
相关产品推荐
相关产品推荐

