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

React调用API报错Cannot read property 'error' of undefined如何处理

问题根因

  1. search方法中检测到查询词为空时,仅执行了清空本地状态的逻辑,未添加return中断后续执行,空查询词依然会调用图书搜索接口。
  2. 空查询请求返回的结果为undefined,代码直接访问result.error属性就会触发类型错误。

修复方案

直接替换原search方法即可,修复点如下:

  • 空查询逻辑块添加return,终止后续接口调用
  • 增加结果存在性判断,兼容接口返回异常的场景
  • 增加Promise catch兜底,避免其他接口异常导致页面崩溃

修复后的代码:

search(event){
  const query = event.target.value;
  if(query.length === 0) {
    this.setState({
        booksAnswer: [],
        noneResult: false
    })
    // 空查询直接返回,不发起后续请求
    return;
  }

  BooksAPI.search(query.trim(), 20).then((result)=>{
    let noneResult = false;
    // 先判断结果是否存在,再判断error字段
    if(!result || result.error){
        noneResult = true;
        result = [];
    }

    const promises = [];
    result.forEach((elem, key)=>{
        promises.push(
            BooksAPI.get(elem.id).then((data)=>{
                result[key]["shelf"] = data.shelf 
            })
        );
    })
    return Promise.all(promises).then(()=>{
        this.setState({
            booksAnswer: result,
            noneResult: noneResult
        })
    });
  }).catch(() => {
    // 所有请求异常统一兜底
    this.setState({
        booksAnswer: [],
        noneResult: true
    })
  })
}

如果你的开发环境支持ES2020+语法,也可以用可选链result?.error替代result && result.error,写法更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:00:01