Nuxt3.4.0更新后在Composable中调用Pinia Store报错如何解决?
Nuxt 3.4.0 后 Composable 中无法使用 Pinia Store 的解决方案
问题说明
Nuxt 3.4.0 版本更新后,在 Composable 中直接调用 Pinia Store 会触发初始化错误。
示例代码:
// 示例 Composable import { useAuthStore } from '~/store/auth-store'; const authStore = useAuthStore(); export function doSomethingWithStore() { return authStore.checkAuthUser; }
运行后报错:
getActivePinia was called with no active Pinia. Did you forget to install pinia? const pinia = createPinia() app.use(pinia) This will fail in production.
问题根源
Nuxt 3.4.0 调整了 Composable 的执行时机,在 Composable 顶层直接调用 useAuthStore() 时,Pinia 实例还未完成初始化,导致无法找到活跃的 Pinia 实例。
修复方案
将 Pinia Store 的调用移到函数内部,确保在组件/Composable 生命周期内(Pinia 已初始化完成)执行:
// 修复后的 Composable import { useAuthStore } from '~/store/auth-store'; export function doSomethingWithStore() { const authStore = useAuthStore(); return authStore.checkAuthUser; }
修改后,useAuthStore() 会在函数执行时被调用,此时 Pinia 实例已就绪,即可正常获取 Store 并调用相关属性。
内容的提问来源于stack exchange,提问作者Jean-Pierre Engelbrecht
相关产品推荐
相关产品推荐

