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

将axios请求结果存入const并返回时遇response.data未定义错误求助

解决axios请求后无法获取response.data的问题

你的问题出在同时混用了await和.then()/.catch(),导致response变量的值并非axios返回的响应对象:

  • .then()里你只执行了console.log,这个函数的返回值是undefined,所以await拿到的就是undefined
  • 后续访问response.data自然会触发undefined is not an object的错误

下面是两种修复方案,按需选择:

方案一:用try/catch替代then/catch(推荐,更符合async函数的写法逻辑)

export async function getCategories() {
  const https = "xxxxxx";
  const url = `${https}/api/Category/GetCategories`;
  const userToken = "xxxxxxxx";
  const authStr = "Bearer ".concat(userToken);

  const options = {
    method: "POST",
    headers: {
      Authorization: authStr,
    },
    url: url,
  };

  try {
    // 直接用await拿到完整的响应对象
    const response = await axios(options);
    console.log(response.data[0].categoryName);
    
    const fetchedCategories = response.data[0];
    console.log("🚀 ~ file: menu.js:27 ~ getCategories ~ fetchedCategories", fetchedCategories);
    
    return fetchedCategories;
  } catch (error) {
    console.log(error.toJSON());
    // 可选:抛出错误让调用方处理,或者返回默认值(比如[])
    throw error;
  }
}

方案二:坚持用then/catch时,确保返回正确数据

如果不想用try/catch,就去掉await,直接返回axios的Promise链,同时在then里返回需要的数据:

export async function getCategories() {
  const https = "xxxxxx";
  const url = `${https}/api/Category/GetCategories`;
  const userToken = "xxxxxxxx";
  const authStr = "Bearer ".concat(userToken);

  const options = {
    method: "POST",
    headers: {
      Authorization: authStr,
    },
    url: url,
  };

  return axios(options)
    .then((response) => {
      console.log(response.data[0].categoryName);
      const fetchedCategories = response.data[0];
      console.log("🚀 ~ file: menu.js:27 ~ getCategories ~ fetchedCategories", fetchedCategories);
      // 必须返回需要的数据,调用函数的地方才能拿到结果
      return fetchedCategories;
    })
    .catch((error) => {
      console.log(error.toJSON());
      throw error;
    });
}

关键注意点

  • 不要在async函数里同时混用await和.then(),会混淆变量的实际返回值
  • 错误处理要彻底,避免出现Possible Unhandled Promise Rejection警告
  • 无论哪种方案,都要确保最终返回你需要的数据,或者正确传递错误给调用方

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:05:43