Vue3+Vite项目执行npm run dev报Cannot access 'store' before initialization如何解决
错误原因
该报错本质是循环依赖导致:你将customAxios、socket实例的定义放在了main.js中,而main.js已经导入了store;如果你的store子模块(loggedInUser/createChat)或者router路由配置里,又从main.js导入了customAxios/socket,就会形成循环加载,此时store还未完成初始化就被访问,触发报错。
另外你代码中app.use(socket)的写法是错误的,socket.io-client实例不是Vue插件,不能直接传入use方法注册。
解决方案
第一步:抽离公共实例消除循环依赖
新建两个工具文件,把和main.js无关的通用实例抽出去:
- 新建
src/utils/request.js存放axios配置:
import axios from 'axios' const token = localStorage.getItem('token') const customAxios = axios.create({ baseURL: 'http://localhost:3000/api', timeout: 10000 }) // 先设置公共请求头 customAxios.defaults.headers.common = { "X-Requested-With": "XMLHttpRequest", 'Content-Type': 'application/json' } // 有token再追加Authorization,避免被覆盖 if (token) { customAxios.defaults.headers.common.Authorization = `Bearer ${token}` } export default customAxios
- 新建
src/utils/socket.js存放socket实例:
import { io } from "socket.io-client" const token = localStorage.getItem('token') export const socket = io("http://localhost:3000/", { reconnectionDelayMax: 10000, auth: { token: token } })
第二步:修改main.js
删掉原有socket、customAxios的定义,修正插件注册逻辑:
import "tailwindcss/tailwind.css" import { createApp } from 'vue' import App from './App.vue' import router from './router' import store from './store' import './index.css' import customAxios from './utils/request' import { socket } from './utils/socket' const app = createApp(App) // 全局挂载实例,组件内可通过this.$axios、this.$socket访问 app.config.globalProperties.$axios = customAxios app.config.globalProperties.$socket = socket // 删掉错误的use(socket)写法 app.use(store).use(router).mount('#app')
第三步:替换导入路径
检查你的store/modules下的两个模块文件、router/index.js文件,把所有从main.js导入customAxios/socket的代码,替换成从上面新建的utils/request.js、utils/socket.js导入即可。
修改完成后重新执行npm run dev即可解决报错。
内容的提问来源于stack exchange,提问作者codingIsLove
相关产品推荐
相关产品推荐

