初步排查了报错原因:我在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'
})
import pinia from "@/stores";
export function useUserStore() {
return useUserDefineStore(pinia);
}
总结:困扰了很多天,也是看别人开源的代码,结合官网的解决方案,一步一步确定方案。有问题可评论交流