[pinia]getActivePinia was called with no active Pinia. Did you forget to install pinia?

getActivePinia was called with no active Pinia. Did you forget to install pinia?

problem

版本:

  • vue3.2 + ts
  • pinia

控制台报错:
pinia.js?v=b2b92fbd:1347 Uncaught Error: []: getActivePinia was called with no active Pinia. Did you forget to install pinia?

reason

我遇到的场景的原因如下:

  • 在定义全局 route.beforeEach 钩子函数时,使用了 pinia 的某个store 触发这个报错
  • 在定义app router 模块时,此时store还没创建好,因此不能使用

solution

将 pinia useStore 从 route.beforeEach 外面 移动到 内部
个人理解:内部方法是异步的方法,当它执行时,route/store都已经创建好

例子:将const { header } = useStore();从router.beforeEach方法外面移动到方法内部

// before 
import useStore from '@/store';
const { header } = useStore();
const router = createRouter({/** 省略 */})
router.beforeEach((to, _, next) => {
  header.changeData({/*xxx*/}) // 使用store上的action
  next();
});
export default router
// after 
import useStore from '@/store';
const router = createRouter({/** 省略 */})
router.beforeEach((to, _, next) => {    
  const { header } = useStore();
  header.changeData({/*xxx*/}) // 使用store上的action
  next();
});
export default router

你可能感兴趣的:(pits,vue.js,前端,javascript)