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

使用fetch替代回调重写代码后出现TypeError报错求助

解决fetch遍历数据时的"Cannot read properties of undefined (reading 'length')"错误

你的问题出在第一个.then回调里——你调用了response.json()但没有把它返回出去,导致第二个.then拿到的data是undefined,自然没法读取length属性。

修正后的代码

runCode.addEventListener("click", ()=>{
    fetch(theUrl)
        .then(response => response.json()) // 单行箭头函数自动返回结果;也可以写成response=>{return response.json()}
        .then((data)=>{
            // 保险起见先判断data是否为数组
            if (Array.isArray(data)) {
                for(let i=0;i<data.length; i++){
                    generateHTML(data[i]);
                }
            }
        })
        .catch(err => console.error('请求或解析出错:', err)); // 捕获Promise链中的错误
});

关键说明

  • 箭头函数如果用大括号包裹代码块,必须显式写return,否则默认返回undefined;单行表达式可以省略大括号,自动返回结果。
  • 加上.catch能捕获请求失败、JSON解析失败等异常,避免控制台出现未捕获的Promise错误。
  • 提前判断data是否为数组,能防止API返回非数组格式时再次触发类似报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 18:42:02