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

ReactJS中transferproduct.js调用接口报读取response属性TypeError错误

React Axios调用接口类型错误修复

错误场景

在React项目transferproduct.js的handleSubmit方法中调用产品查询接口时,控制台抛出类型错误:

transferproduct.js:38 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'response')
    at handleSubmit (transferproduct.js:38:1)

报错位置为代码第38行读取datas.response的逻辑段。

对应出错的代码片段:

const { datas } = await axios.get(
      "http://localhost:8080/api/QueryProductById/"+data.id
    );

    let parseData = JSON.parse(datas.response);

    setProduct(parseData);

查询ID为1的产品时,接口实际返回内容如下:

{"response":"{\"id\":\"1\",\"name\":\"Product1\",\"area\":\"gfg\",\"ownerName\":\"gf\",\"cost\":\"1000\"}"}

错误原因

  • Axios 请求返回的标准响应结构中,服务端下发的业务数据统一挂载在data字段,响应对象本身不存在datas属性
  • 原代码错误解构了不存在的datas字段,得到的变量值为undefined,尝试读取undefined的response属性就会触发上述类型错误

修复方法

把解构的字段名从错误的datas改成Axios标准的data即可,修正后可正常运行的代码:

// 修正:解构响应对象的data字段,拿到接口返回的完整业务数据
  const { data } = await axios.get(
      "http://localhost:8080/api/QueryProductById/"+data.id
    );
    // 从业务数据中读取response字段,解析内部存储的产品JSON字符串
    let parseData = JSON.parse(data.response);

    setProduct(parseData);

补充提示:Axios默认会自动解析JSON格式的接口响应,不需要手动对最外层返回结果做JSON.parse处理;仅当字段值本身是字符串化的JSON内容时(比如本次返回的response字段值),才需要额外调用JSON.parse做转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 23:16:30