安装pinia官方文档和uniapp vue3版本,main.js文件如下:
import { createPinia } from 'pinia'
import { createSSRApp } from 'vue'
import App from './App.vue'
export function createApp() {
const app = createSSRApp(App)
const pinia = createPinia();
app.use(pinia)
return {
app
}
}
结果编译成功,运行报错:
13:33:26.965 reportJSException >>>> exception function:createInstanceContext, exception:white screen cause create instanceContext failed,check js stack ->Uncaught Error: [?]: getActivePinia was called with no active Pinia. Did you forget to install pinia?
13:33:27.028 const pinia = createPinia()
13:33:27.068 app.use(pinia)
13:33:27.120 This will fail in production.
一头雾水,明明已经安装了,为什么提示没有安装呢?
网上搜了一圈,uniapp 与 pinia 两个关键字关联的结果少之又少,最终尝试从源码中找寻答案。
从unaipp官方文档中得知,vue3版本使用ssr模式创建应用,渲染速度更快。
所以,在使用pinia上,也应该注意,使用相应的规范。
在Server-Side Rendering (SSR)章节中,是这么写的:
Creating stores with Pinia should work out of the box for SSR as long as you call your useStore() functions at the top of setup functions, getters and actions:
export default defineComponent({
setup() {
// this works because pinia knows what application is running inside of
// `setup()`
const main = useMainStore()
return { main }
},
})
If you need to use the store somewhere else, you need to pass the pinia instance that was passed to the app to the useStore() function call:
const pinia = createPinia()
const app = createApp(App)
app.use(router)
app.use(pinia)
router.beforeEach((to) => {
// ✅ This will work make sure the correct store is used for the
// current running app
const main = useMainStore(pinia)
if (to.meta.requiresAuth && !main.isLoggedIn) return '/login'
})
按照我的理解就是,在setup函数中直接使用useStore函数是没有问题的,因为setup的生命周期之前就已经完成了pinia的初始化了,但是,如果你要在setup函数之外使用pinia,这就需要自己手动创建pinia对象。但是检查一番后,发现并不是这个问题。
最后实在没办法,回滚到上一个没使用pinia的版本,然后再一步步往下走,发现是有个页面中在data()函数之前就使用了useStore方法,报错的意思就是说pinia初始化还没完成,就开始使用了。不得不说,uniapp的错误提示还真是少的可怜,完全摸不到边,之后还是要学聪明点,写一步,调试一步。