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

在对象数组中查找属性报错:无法读取undefined的'options'属性

解决"cannot read property 'options' of undefined"错误

这个错误的根源很明确:当你调用categories.find(category => category.id == setParentCategory)时,没有找到匹配的category对象,所以返回了undefined,这时候再去访问.options自然就会抛出这个报错。

常见的触发场景有两种:

  • setParentCategory的值和数组中所有category.id都不匹配(比如类型不匹配,比如id是数字但setParentCategory是字符串)
  • setParentCategory的初始值是null/undefined,虽然你有setParentCategory ? ... : null的判断,但可能在某些状态切换时依然会进入find逻辑

具体解决方案

1. 给find结果加安全访问兜底

最直接的修复是使用可选链操作符?.,同时配合默认空数组,避免undefined的问题:

{setParentCategory ? 
  <Picker 
    selectedValue={setSubCategory} 
    label="Year group" 
    onChange={this.onGroupChange} 
    options={ categories.find(category => category.id === setParentCategory)?.options || [] } 
  /> 
: null}

这里的?.options会在find结果为undefined时直接返回undefined,再通过|| []给Picker一个空数组作为默认值,保证组件不会因为options为undefined而报错。

2. 确保类型严格匹配

注意你数组里的id是数字类型,如果setParentCategory是字符串类型(比如从URL参数、表单输入获取的),==的隐式转换可能偶尔失效,建议用===严格相等,并手动转换类型:

categories.find(category => category.id === Number(setParentCategory))?.options || []

3. 提前缓存查找结果(更易维护)

如果逻辑复杂,建议先把找到的category缓存下来,再做判断,代码可读性更高:

const currentCategory = categories.find(category => category.id === setParentCategory);

return (
  {setParentCategory && currentCategory ? 
    <Picker 
      selectedValue={setSubCategory} 
      label="Year group" 
      onChange={this.onGroupChange} 
      options={currentCategory.options} 
    /> 
  : null}
)

额外检查点

  • 确认setParentCategory的初始值:如果初始是0以外的数字/其他值,要确保数组里有对应的id
  • 可以在控制台打印setParentCategory和categories,确认两者的匹配关系,排查是否存在值不匹配的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:54:30