Vue3/Pinia:组合式函数中调用useStore()抛出TypeError问题
Vue3 + Pinia 组合式函数调用 useStore 报错解决方案
问题详情
运行Vite编译的Vue3单页应用时,在组合式函数中调用useStore()会触发Pinia类型错误:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '_s')
该store在应用其他组件中使用正常,问题根源是组合式函数执行过早,此时Pinia实例还未完成初始化挂载。
复现步骤
- 创建测试Store:
import { ref } from 'vue' import type { Ref } from 'vue' export const useTestStore = defineStore('customer-portal', () => { console.log('Defining Teststore...') const test: Ref<string> = ref('') return { test, } })
- 在组合式函数顶层直接调用Store:
import { ref } from 'vue' import { useTestStore } from '@/vue/store/test' // 顶层直接调用导致报错 const store = useTestStore()
- 在组件中引入并使用该组合式函数
解决办法
1. 移至Vue生命周期钩子内调用
不要在组合式函数的顶层作用域直接初始化Store,而是将useStore()调用放到组件生命周期钩子(如onMounted)或具体业务函数内部:
import { ref, onMounted } from 'vue' import { useTestStore } from '@/vue/store/test' let store: ReturnType<typeof useTestStore> | null = null onMounted(() => { // 确保Pinia实例就绪后再初始化Store store = useTestStore() }) // 或在需要操作Store的函数内调用 const updateTestValue = () => { const currentStore = useTestStore() currentStore.test = 'new value' }
2. 手动传入Pinia实例(特殊场景使用)
如果必须在组合式函数顶层处理,可以通过inject获取Pinia实例后再调用useStore,同时要做好空值判断:
import { ref, inject } from 'vue' import { useTestStore } from '@/vue/store/test' import type { Pinia } from 'pinia' // 从Vue注入容器中获取Pinia实例 const pinia = inject<Pinia>('pinia') // 仅当Pinia存在时初始化Store const store = pinia ? useTestStore(pinia) : null
注意:此方法依赖Pinia已通过app.use(pinia)挂载到Vue应用实例,否则inject会返回undefined。
3. 调整组合式函数的导入时机
避免在应用入口文件(如main.ts)或提前执行的模块中直接导入并执行该组合式函数,确保它仅在组件内部被调用,保证Pinia实例已完成初始化。
内容的提问来源于stack exchange,提问作者btsfreak
相关产品推荐
相关产品推荐

