Fetch/Then调用链行为异常求助
嘿,这问题我太熟了!咱们一步步拆解来看~
核心根源:Promise的then链是靠返回值传递数据的
你得先搞懂一个关键规则:每个then回调函数的返回值,就是下一个then接收的参数。如果你的回调里没写return,那默认会返回undefined,下一个then自然就拿不到数据了。
为什么两次console.log(data)会一正常一undefined?
我猜你是把原来的单个then拆成了两个,代码大概是这样:
fetch('你的接口地址') .then(res => res.json()) .then(data => { console.log(data); // 第一次能打印,因为这里的data是接口返回的正常数据 // 这里没写return,所以这个then默认返回undefined }) .then(data => { console.log(data); // 这里的data就是前一个then返回的undefined })
对,就是这么回事!第一个then的回调没返回任何值,所以下一个then接收到的就是undefined。
为什么原代码里data.unshift(...)会报错?
先看unshift本身:它会修改原数组,但返回值是数组修改后的长度(一个数字),不是修改后的数组。不过你说提示data未定义,那大概率是前面的then出了问题——比如你漏写了return:
// 错误示例:漏写return,导致下一个then的data是undefined fetch('你的接口地址') .then(res => { res.json(); // 这里没return,所以这个then返回undefined }) .then(data => data.unshift(this.state.emptyDirections)) // data是undefined,直接报错
怎么解决?
给你两个关键修正点:
- 确保每个
then都返回需要传递的数据:如果要修改数组并传给下一个then,别直接返回data.unshift(...),先修改再return数组本身:.then(data => { data.unshift(this.state.emptyDirections); return data; // 显式返回修改后的数组 }) - 检查前一个
then是否正确返回了数据:比如res.json()一定要被return,要么直接写.then(res => res.json())(箭头函数会隐式return),要么在大括号里写return res.json()。
最后给你一个完整的正确示例,别忘了加catch捕获错误,排查问题更方便:
fetch('你的接口地址') .then(response => { if (!response.ok) { throw new Error('请求失败啦'); } return response.json(); // 必须return,否则下一个then拿不到数据 }) .then(data => { data.unshift(this.state.emptyDirections); return data; // 返回修改后的数组 }) .then(modifiedData => { console.log('处理后的数据:', modifiedData); // 这里可以继续做你要的操作,比如更新state }) .catch(error => { console.error('出问题了:', error); });
内容的提问来源于stack exchange,提问作者Peter Breen
相关产品推荐
相关产品推荐

