Laravel11+Vue+Inertia SSR模式下Pinia激活报错求助
解决Laravel 11+Vue+Inertia SSR模式下Pinia "getActivePinia()" 报错问题
问题根源
SSR模式下,每个请求都是独立隔离的,不能复用全局Pinia实例。你在App.vue的setup中直接创建Pinia,会导致实例共享或在useStore调用时Pinia尚未挂载到当前Vue实例上——客户端渲染时组件挂载流程和SSR不同,客户端能保证Pinia先被挂载,但SSR的服务端渲染流程中,组件setup执行时机可能早于Pinia的挂载绑定。
解决方案
1. 移除App.vue中的Pinia创建逻辑
删除App.vue里的createPinia()调用,useAppStore()直接使用即可,Pinia的初始化统一放到入口文件中处理。
修改后的App.vue示例:
<script setup> import { useAppStore } from '@/stores/app' // 直接使用store,无需在组件内创建Pinia const appStore = useAppStore() // 其他业务逻辑 </script>
2. 正确配置SSR入口文件(ssr.js)
为每个请求创建独立的Pinia实例,并挂载到Vue应用上,同时将服务端的Pinia状态序列化后传递给客户端:
import { createSSRApp, h } from 'vue' import { createPinia } from 'pinia' import { createInertiaApp } from '@inertiajs/vue3' import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers' export default function handleRequest(request, response) { return createInertiaApp({ request, resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')), setup({ App, props, plugin }) { // 为当前请求创建全新的Pinia实例 const pinia = createPinia() return createSSRApp({ render: () => h(App, props) }) .use(plugin) .use(pinia) }, // 将服务端Pinia状态注入到页面props,供客户端恢复 onRendered(page) { const pinia = createPinia() page.props.piniaState = JSON.stringify(pinia.state.value) }, }) }
3. 客户端入口文件(main.js)恢复Pinia状态
客户端初始化时,读取服务端传递的状态并恢复到Pinia中:
import { createApp, h } from 'vue' import { createPinia } from 'pinia' import { createInertiaApp } from '@inertiajs/vue3' import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers' createInertiaApp({ resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')), setup({ App, props, plugin }) { const pinia = createPinia() const app = createApp({ render: () => h(App, props) }) .use(plugin) .use(pinia) // 恢复服务端传递的Pinia状态 if (props.initialPage.props.piniaState) { pinia.state.value = JSON.parse(props.initialPage.props.piniaState) } return app }, })
4. 检查全局调用时机
确保所有useStore()的调用都发生在Pinia被app.use(pinia)挂载之后,比如避免在路由守卫、全局自定义指令等提前执行的逻辑中未挂载Pinia就调用store。
内容的提问来源于stack exchange,提问作者Canelo Digital
相关产品推荐
相关产品推荐

