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

Uncaught (in promise) TypeError错误排查:data.forEach为何不是函数?

解决Uncaught (in promise) TypeError: data.forEach is not a function错误

你的推测完全正确,SWAPI返回的不是直接的行星数组,而是一个包含results字段的对象,results才是存储行星数据的数组。另外原代码里的try/catch位置错误,根本无法捕获异步请求的异常,需要调整位置。

修改后的代码如下:

async function getPlanets() {
  try {
    let response = await fetch('https://swapi.py4e.com/api/planets/');
    let data = await response.json();
    return data;
  } catch (error) {
    console.log(error);
  }
}

getPlanets().then(data => {
  // 提取results数组进行遍历
  data.results.forEach(planet => {
    const markup = `<li>${planet.name}</li>`;
    document.querySelector('ul').insertAdjacentHTML('beforeend', markup);
  });
});

关键修改说明:

  • 将try/catch移入getPlanets函数内部,这样才能捕获fetch和response.json()过程中可能出现的异常
  • 在then回调中,通过data.results获取真正的行星数组,再调用forEach遍历渲染

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:42:02