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

如何全局存储并访问Axios请求返回的数据?

全局存储Axios异步数据的解决办法

你现在的问题是异步代码执行顺序导致的:data1()是异步函数,里面的await data()会等待Axios请求完成,但data1()本身调用后不会阻塞后续代码,所以你紧接着的console.log(resp)会在请求还没返回时执行,此时resp还没被赋值,自然是undefined。

下面是几种可行的解决方式:

方案1:顶层使用async/await(支持的环境)

如果你的运行环境支持顶层await(比如Node.js 14.8+、现代浏览器的ES模块),可以直接把初始化逻辑封装成异步函数,确保数据加载完成后再访问:

let resp;
const data = () => {
  return axios.get(`http://localhost:3000/s/api/v1/events/data?`)
}

async function init() {
  resp = await data();
  console.log(resp); // 这里能拿到预期数据
  // 其他需要使用resp的函数也可以在这里调用
  useRespData();
}

function useRespData() {
  console.log(resp); // 正常访问全局存储的数据
}

init();

方案2:用.then()处理异步结果

如果不支持顶层await,就利用Axios返回Promise的特性,通过.then()链式调用确保数据加载完成后再操作:

let resp;
const data = () => {
  return axios.get(`http://localhost:3000/s/api/v1/events/data?`)
}

data().then(res => {
  resp = res;
  console.log(resp); // 拿到预期数据
  useRespData(); // 调用需要使用数据的函数
});

function useRespData() {
  console.log(resp); // 正常访问全局数据
}

方案3:封装成全局可调用的异步函数

不想依赖全局变量的话,可以封装一个异步函数,每次需要数据时直接调用并等待结果:

const fetchData = async () => {
  const res = await axios.get(`http://localhost:3000/s/api/v1/events/data?`);
  return res;
}

// 任何需要数据的地方调用这个函数
async function anotherFunction() {
  const resp = await fetchData();
  console.log(resp); // 正常使用请求到的数据
}

内容的提问来源于stack exchange,提问作者Tech Learn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 04:57:01