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

Vue中如何获取数据库真实ID而非默认ID?附报错排查

问题分析与修复方案

1. 为什么会出现TypeError: Cannot convert undefined or null to object?

你把fetch返回的Promise对象直接赋值给了snapshot,但fetch的Promise只有在then回调里才会拿到真正的响应数据。第二个then里你试图访问snapshot.data,但snapshot是Promise实例,根本没有data属性,所以snapshot.data是undefined,调用Object.keys(undefined)自然会抛出这个错误。

2. 页面ID与数据库不一致的原因

你错误地把遍历对象时的索引键key赋值给了appData.id,这个key不是数据库返回的真实ID;再加上前面的数据源错误(用了不存在的snapshot.data),最终显示的ID肯定和数据库对不上。

修复后的代码

getAllEvents() {
  var requestOptions = {
    method: "GET",
    redirect: "follow",
  };

  fetch("http://localhost:8080/event/getAllData", requestOptions)
    .then((response) => response.json()) // 直接解析JSON,不用先转文本再解析
    .then((result) => {
      console.log(result);
      const events = [];
      // 遍历接口返回的真实数据对象
      Object.keys(result).forEach((key) => {
        let appData = result[key];
        // 优先用数据本身带的数据库ID,没有的话再用对象键(如果键是数据库ID的话)
        appData.id = appData.id || key;
        events.push(appData);
      });
      this.events = events;
    })
    .catch((error) => console.log("error", error));
}

关键修正点

  • 删掉了没用的snapshot变量,直接用then回调里的result(已解析为JSON的真实响应数据)
  • 用response.json()替代response.text()+JSON.parse,更简洁可靠
  • 修正ID赋值逻辑:优先取数据自带的数据库ID,避免用遍历索引键冒充ID

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:25:20