You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Axios多then链式调用第二个then返回undefined问题排查求助

解决Axios链式调用中第二个then返回undefined的问题

嘿,这个问题我之前也踩过坑,核心原因其实很简单——Promise链式调用是靠每个then的返回值传递数据的,你的第一个then里没返回任何内容,第二个then自然就拿到undefined啦!

问题到底出在哪?

先看你的代码片段:

.get('https://api.tvmaze.com/singlesearch/shows', {
  params: {
    q: id,
  },
})
.then((res) => setOneShow([res.data])) // 这里没有返回值!
.then((res) => console.log(res)); // 所以res是undefined

setOneShow应该是React的状态更新函数吧?这类函数本身是没有返回值的,当第一个then执行完后,默认会返回undefined,第二个then接收的就是这个undefined,自然拿不到你想要的ID数据。

怎么修复?

给你两种简单的解决方案,按需选择:

方案1:在第一个then里返回需要的数据

如果你就是想拆分两步操作,只要在第一个then里把接口返回的数据(或者你需要的ID)返回出去就行:

.get('https://api.tvmaze.com/singlesearch/shows', {
  params: {
    q: id,
  },
})
.then((res) => {
  setOneShow([res.data]);
  return res.data; // 把数据传递给下一个then
})
.then((showData) => {
  console.log(showData.id); // 现在就能拿到你要的ID啦!
});

方案2:合并逻辑到同一个then

如果不需要拆分两步,直接把状态更新和打印操作放在同一个then里更直观,也不会踩返回值的坑:

.get('https://api.tvmaze.com/singlesearch/shows', {
  params: {
    q: id,
  },
})
.then((res) => {
  const showData = res.data;
  setOneShow([showData]);
  console.log(showData.id); // 直接在这里获取并打印ID
});

额外推荐:用async/await写法更清晰

如果你的代码环境支持,换成async/await的写法,可读性会更高,也更容易维护:

async function fetchSingleShow(id) {
  try {
    const res = await axios.get('https://api.tvmaze.com/singlesearch/shows', {
      params: { q: id }
    });
    const showData = res.data;
    setOneShow([showData]);
    console.log(showData.id);
  } catch (error) {
    console.error('请求出错了:', error);
  }
}

测试验证

你可以用q=Grimm测试接口,返回的数据里明确包含id字段(比如Grimm的ID是82),按照上面的方式调整后,就能顺利获取到你需要的数据啦!

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

火山引擎 最新活动