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

点击复选框触发TypeError: Cannot read properties of undefined (reading 'includes')的解决方法

问题解决:Cannot read properties of undefined (reading 'includes')

你的问题核心是部分产品数据的model字段未定义——虽然大部分API返回的数据包含该字段,但存在边缘情况(比如某些产品没有model值),导致调用includes时触发报错。

直接修复代码的两种方式:

方式1:使用可选链操作符(推荐)

通过?.安全访问model的includes方法,当p.model为undefined或null时,表达式直接返回undefined,!undefined会被判定为true,从而过滤掉这些无model的产品:

// Consignment Only
if (filters.consignmentOnly && !p.model?.includes("CONSIGNMENT")) {
  return false;
}

方式2:显式判断model存在性

先检查p.model是否有效,再调用includes,逻辑和上面一致:

// Consignment Only
if (filters.consignmentOnly && (!p.model || !p.model.includes("CONSIGNMENT"))) {
  return false;
}

从根源避免问题:预处理API数据

在获取到API返回的产品列表后,统一给每个产品的model字段设置默认空字符串,确保后续所有操作都不会遇到undefined:

// 假设products是API返回的原始数组
const processedProducts = products.map(product => ({
  ...product,
  model: product.model ?? "" // 仅当model为null/undefined时设为空字符串
}));

TypeScript类型优化(可选)

如果项目使用TypeScript,可以调整产品类型定义,明确model的可选性,避免类型报错:

interface Product {
  model?: string; // 标记model为可选字段
  // 其他产品字段...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:55:18