You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3组合式API+Vuex中Axios配置文件无法访问Store的问题

问题原因及解决方案

核心问题

你遇到的问题有两个关键原因:

  1. useStore钩子的使用场景错误:useStore是Vue3组合式API的专属钩子,只能在组件的setup函数、自定义钩子中调用,不能直接在普通JS模块(比如你的http.js)的顶层作用域执行——此时Vue应用实例还未创建,钩子无法获取到store上下文,自然返回undefined。
  2. 循环依赖:你的store/index.js导入了http,同时http.js又导入了store,模块加载时互相等待,导致store实例无法正常初始化。

修复步骤及代码示例

1. 修正http.js的store引用方式

直接导入store实例(而非useStore钩子),因为你的store/index.js导出的是已经创建好的Vuex Store实例:

import axios from "axios";
// 直接导入store实例,不是useStore钩子
import store from "@/stores/index.js";

const http = axios.create({
    baseURL: "https://challenge.spexa.dev/"  
})

http.interceptors.request.use(function (config) {
    console.log("store", store) // 现在能正常拿到store实例
    const token = store.getters['token']
  
    if (token) {
        config.headers.Authorization = 'Bearer ' + token;
    }
    return config;
});
  
export default http

2. 解决循环依赖

移除store/index.js中对http的导入,如果需要在store的actions中使用axios,改为在actions内部局部导入:

import Vuex from "vuex";

// 移除http的全局导入,避免循环依赖
export default new Vuex.Store({
  state: {
    access_token: null,
    refresh_token: null,
  },

  getters: {
    token(state) {
      return state.access_token
    }
  },

  // 如果需要在actions中调用axios,局部导入http
  actions: {
    async fetchSomeData({ commit }) {
      // 局部导入避免循环依赖
      const http = await import('../services/http');
      const response = await http.default.get('/api/data');
      // 后续逻辑...
    }
  }
});

内容的提问来源于stack exchange,提问作者morteza mortezaie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 06:41:18