Vue Uncaught ReferenceError: Cannot access 'store' before initializatio
app.ts:106 Uncaught ReferenceError: Cannot access 'store' before initialization
at useAppStoreHook (app.ts:106:22)
at index.ts:8:18

如你的代码中已经做的 () => import(...)),并且不会在导入时立即访问 store
问题原因
在 privateRoutes 中,你直接引用了 layout:
component: layout, // ❌ 直接引用导入的组件
而 layout 是通过 静态导入 的:
import layout from "@/layout/index.vue"; // 静态导入(立即执行)
这会导致 layout 组件在路由初始化时就被解析,如果 layout 内部或它依赖的模块(如 Pinia store)还未初始化,就会报错 Cannot access 'store' before initialization。
正确做法
应该使用 动态导入(懒加载) 的方式:
component: Layout, // ✅ 使用动态导入的函数
其中 Layout 是一个返回 import() 的函数:
export const Layout = () => import("@/layout/index.vue"); // 动态导入(懒加载)
修复代码
1. 修改 privateRoutes 使用 Layout
export const privateRoutes: RouteRecordRaw[] = [
{
path: "/custodyOrder",
component: Layout, // ✅ 使用动态导入的 Layout
redirect: "/custody-order",
name: "CustodyOrder",
children: [
// ...子路由
],
},
];
2. 确保 Layout 是动态导入的
// 正确导出动态导入的 Layout
export const Layout = () => import("@/layout/index.vue");
3. 移除静态导入的 layout
删除或注释掉:
// ❌ 移除或注释掉(避免静态导入)
// import layout from "@/layout/index.vue";
为什么这样能解决问题?
| 方式 | 行为 | 是否影响初始化顺序 |
|---|---|---|
component: layout(静态导入) |
立即加载 layout 组件,如果组件内部访问了未初始化的 Pinia store,就会报错 |
❌ 会导致 store 访问过早 |
component: Layout(动态导入) |
延迟加载 layout 组件,仅在路由被访问时才加载,此时 Pinia 已经初始化 |
✅ 安全 |
完整修正后的代码
router.ts
import type { App } from "vue";
import { createRouter, createWebHashHistory, type RouteRecordRaw } from "vue-router";
// ✅ 使用动态导入的 Layout
export const Layout = () => import("@/layout/index.vue");
// ❌ 移除静态导入
// import layout from "@/layout/index.vue";
export const privateRoutes: RouteRecordRaw[] = [
{
path: "/custodyOrder",
component: Layout, // ✅ 使用动态导入
redirect: "/custody-order",
name: "CustodyOrder",
children: [
{
path: "/custody-order",
component: () => import("@/views/custody-order/index.vue"),
meta: { title: "监测单", icon: "el-icon-monitor" },
},
],
},
];
export const constantRoutes: RouteRecordRaw[] = [
// ...其他路由
];
const router = createRouter({
history: createWebHashHistory(),
routes: constantRoutes,
});
export function setupRouter(app: App<Element>) {
app.use(router);
}
export default router;
main.ts(确保 Pinia 先初始化)
import { createApp } from "vue";
import { createPinia } from "pinia";
import App from "./App.vue";
import router from "./router";
const app = createApp(App);
// 先 Pinia,后 Router
app.use(createPinia());
app.use(router);
app.mount("#app");
关键点总结
- 静态导入(
import X from "...")- 会在代码加载时立即执行,可能导致 store 未初始化时就被访问。
- 动态导入(
() => import("..."))- 延迟加载组件,确保 Pinia 已经初始化 后才执行。
- 路由组件尽量用动态导入
- 避免在路由配置中直接引用静态导入的组件,除非确定它不依赖 store。
这样修改后,Cannot access 'store' before initialization 问题应该就能解决! 🎯
本文来自博客园,作者:VipSoft 转载请注明原文链接:https://www.cnblogs.com/vipsoft/p/19032004
浙公网安备 33010602011771号