pinia访问其他store的action报错:未初始化调用getActivePinia()

pinia访问其他store的action报错:未初始化调用getActivePinia()

报错信息

初步排查了报错原因:我在useUserStore里面调用的别的store的action,就会导致报错未初始化。还有一个点就是我在路由导航router.beforeEach中使用了useUserStore,取消调用就不报错。
在这里插入图片描述

pinia.js?v=e91dc4f7:1355 Uncaught Error: [🍍]: "getActivePinia()" was called but there was no active Pinia. Are you trying to use a store before calling "app.use(pinia)"?
See https://pinia.vuejs.org/core-concepts/outside-component-usage.html for help.
This will fail in production.
    at useStore (pinia.js?v=e91dc4f7:1355:13)
    at tabs.ts:8:24

官网提及:在 setup() 外部使用 store

如果你需要在其他地方使用 store,你需要将原本被传递给应用pinia 实例传递给 useStore() 函数:

const pinia = createPinia()
const app = createApp(App)

app.use(router)
app.use(pinia)

router.beforeEach((to) => {
  // ✅这会正常工作,因为它确保了正确的 store 被用于
  // 当前正在运行的应用
  const main = useMainStore(pinia)

  if (to.meta.requiresAuth && !main.isLoggedIn) return '/login'
})

解决方法:给每个store导出的传递pinia实例

import pinia from "@/stores";
export function useUserStore() {
  return useUserDefineStore(pinia);
}

在这里插入图片描述

总结:困扰了很多天,也是看别人开源的代码,结合官网的解决方案,一步一步确定方案。有问题可评论交流

最近更新

  1. TCP协议是安全的吗?

    2024-01-16 15:42:07       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-16 15:42:07       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-16 15:42:07       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-16 15:42:07       20 阅读

热门阅读

  1. openssl3.2 - 官方demo学习 - pkey - EVP_PKEY_DSA_keygen.c

    2024-01-16 15:42:07       30 阅读
  2. Linux ldd/ld/ldconfig命令

    2024-01-16 15:42:07       29 阅读
  3. mac 系统中vscode 返回上一次文件编辑位置快捷键

    2024-01-16 15:42:07       40 阅读
  4. vscode 调试 php项目

    2024-01-16 15:42:07       40 阅读