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

Bootstrap Table formatter报undefined错误但数据显示正常的求助

问题排查与解决办法

报错原因分析

这个错误本质是appliance.activeAppliance为undefined时,代码直接访问warrantyDurationType导致的。哪怕用v-if控制表格渲染,Bootstrap Table的内部机制可能会在数据未完全就绪时提前调用formatter或sortByFormatted函数;另外也有可能接口返回的某条设备数据里,activeAppliance字段本身就缺失。

具体解决办法

在formatter和sortByFormatted函数里,给每一层对象访问加上可选链操作符?.,同时补充默认值处理,确保不会因为某一层为undefined而抛出错误:

修改后的字段配置代码:

{
  key: 'activeAppliance.warrantyDuration',
  label: this.$t('warrantyDuration'),
  sortable: true,
  formatter: (warrantyDuration, applianceId, appliance) => {
    // 先确保activeAppliance存在,再取warrantyDurationType
    const durationType = appliance?.activeAppliance?.warrantyDurationType;
    const typeText = durationType 
      ? this.$t(`model.appliance.warrantyDurationTypes.${durationType}`).toLocaleLowerCase(this.$i18n.locale)
      : '';
    return `${this.$n(warrantyDuration)} ${typeText}`;
  },
  sortByFormatted: (warrantyDuration, applianceId, appliance) => {
    // 同样先判断activeAppliance和warrantyDurationType是否存在
    const durationType = appliance?.activeAppliance?.warrantyDurationType;
    return durationType === 'YEARS' ? (warrantyDuration * 12) : warrantyDuration;
  }
}

额外检查点

  • 可以在接口数据返回后,先过滤掉activeAppliance为undefined的条目,或者给这些条目补充默认的activeAppliance空对象,避免后续处理出错:
    // 假设接口返回的数据存在this.applianceList中
    this.applianceList = res.data.map(item => ({
      ...item,
      activeAppliance: item.activeAppliance || {}
    }));
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:56:07