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

axios两种写法结果异常:try/catch中res.data为undefined的原因排查

axios异步请求使用try/catch时res.data为undefined的原因分析

我在开发应用时遇到了axios相关问题:

正常运行的代码

let categoryId = ''

axios.get('/api/max')
    .then((res) => {
        console.log(res.data)
        categoryId = res.data.id
    })
    .catch((err) => {
        console.log('ssssssuuuuu')
    })

接口/api/max返回拥有最大ID的分类,这段代码能正常输出res.data。

运行异常的代码

try {
    const res = axios.get('/api/max')
    console.log(res)
    console.log(res.data) // undefined
    categoryId = res.data.id
    console.log('a')
} catch (err) {
    console.log(err.message)
}

这段代码里控制台能输出res,但res.data显示undefined。


问题原因

核心在于axios.get()是异步操作,它返回的是一个Promise对象,而非直接的接口响应结果:

  • 第一段代码用.then()回调,这是Promise的标准用法:只有当请求成功完成后,才会把真实的响应对象传入.then的回调函数,此时的res才包含data属性。
  • 第二段代码直接赋值const res = axios.get('/api/max'),拿到的是一个未完成状态的Promise实例,这个Promise对象本身没有data属性,所以res.data自然是undefined。

修正方案

要让try/catch配合axios正常工作,必须用async/await等待Promise完成,代码如下:

let categoryId = ''

async function fetchCategoryId() {
  try {
    // await等待Promise完成,此时res才是真实的响应对象
    const res = await axios.get('/api/max')
    console.log(res)
    console.log(res.data)
    categoryId = res.data.id
    console.log('a')
  } catch (err) {
    console.log(err.message)
  }
}

fetchCategoryId()

注意:await关键字必须放在标记为async的函数内部才能使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:32:17