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

向数组推送Axios响应数据后无法访问新数据的问题排查

问题分析与解决

你遇到的问题核心有两个:

  1. dataArray是数组而非对象:你试图访问dataArray.data,但数组本身没有.data属性,这直接触发了控制台报错。
  2. 推送的数据结构错误:Axios返回的response.data是一个包含data数组的对象,你现在把整个对象push到了dataArray里,而非对象内的消息数组元素。

修正后的代码

const dataArray = [
    {
      avatarSrc: 'https://themes.mintycodes.com/quicky/assets/media/avatar/2.png',
      name: 'Catherine Richardson',
      time: 'Just now',
      message: 'I didn’t catch that. Could you please repeat?'
    },
    {
        avatarSrc: 'https://themes.mintycodes.com/quicky/assets/media/avatar/2.png',
        name: 'Catherine Richardson',
        time: 'Just now',
        message: 'I didn’t catch that. Could you please repeat?'
      },
    // 可添加更多对象
  ];

axios.get('http://localhost:8000/chat/',{ withCredentials: true })
  .then(response => {
    // 将响应里的消息数组元素逐个添加到dataArray
    dataArray.push(...response.data.data);
    console.log("dataArray", dataArray);
    
    // 获取刚推送的元素的id
    const newIds = response.data.data.map(item => item.id);
    console.log("newly pushed data ids", newIds);
  }) 
  .catch(error => {
    console.error(error);
  })

关键修正说明

  • 使用push(...response.data.data):通过扩展运算符...把响应内的消息数组拆分为单个元素,逐个添加到dataArray,避免把整个带data属性的对象塞入数组。
  • 直接提取接口返回的id:如果只需要新获取的id,直接遍历response.data.data即可,无需从dataArray中筛选,更高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 07:22:45