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

ReactJS报错:Cannot convert undefined or null to object 问题解决

问题解决:Cannot convert undefined or null to object 错误修复

你的报错根源在于newata?.GearCategories可能是undefined/null,或者它的属性值里存在undefined,导致Object.values()无法处理非对象参数,同时过滤逻辑也没跳过无效的chunk项。以下是具体修复方案:

核心修改点

  • 确保Object.values()的参数始终是有效对象:用空值合并运算符??兜底空值
  • 过滤掉chunk为undefined的无效项
  • 安全获取label,避免数组为空时触发报错

修改后的代码

const categorizedDatas2 = maam.reduce((acc, curr) => {
    const { id, Category, CategoryId, SubCategory, SubCategoryId, Name, Brand, Owner, RealOwner, packingLocation, Quantity, Weight, Status } = curr;
    // 兜底空值,确保Object.values始终接收对象参数
    const categoryValues = Object.values(newata?.GearCategories ?? {});
    // 先过滤undefined的chunk,再匹配CategoryId
    const categorymatch = categoryValues.filter(chunk => chunk && chunk.id === CategoryId);
    // 用可选链安全获取label,防止数组为空时报错
    const realcat = categorymatch[0]?.label;
    if (!acc[Owner]) {
      acc[Owner] = {
        items: [],
      };
    }
    acc[Owner].items.push({ id, Category, CategoryId, SubCategory, SubCategoryId, Name, Brand, Owner, RealOwner, packingLocation, Quantity, Weight, Status });
    return acc;
  }, {});

额外补充

如果业务需要realcat不能为undefined,可以给它设置默认值:

const realcat = categorymatch[0]?.label ?? '未分类';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 07:42:42