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

MUI Autocomplete报Cannot read properties of undefined错误

报错原因

报错出现在组件首次渲染阶段,和MongoDB存储的数据格式无关:

  • 初始categories状态被设置为空数组[],组件第一次挂载时,axios异步请求还未返回结果,此时categories长度为0
  • 代码里写死了defaultValue={[categories[3]]},空数组访问索引3的返回值是undefined
  • Autocomplete渲染默认选中项时,会调用getOptionLabel方法读取选项的name字段,传入的参数是undefined,直接读取属性就会触发Cannot read properties of undefined (reading 'name')错误
  • 就算接口请求完成,如果返回的分类数组长度不足4,categories[3]依然是undefined,还是会触发相同报错。
修复方法

做两层防护即可解决问题:

  1. 给getOptionLabel增加空值兜底,避免传入非法值时直接报错
  2. 设置默认值前先判断对应选项是否存在,不要直接硬编码取数组索引赋值,有条件的话优先用分类唯一ID匹配默认项,比固定索引更稳定

修复后的完整代码:

export default function ChooseCat() {
  const [categories, setCats] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const getCats = async () => {
      try {
        const res = await axios.get("/categories");
        setCats(res.data);
      } catch (err) {
        console.error("分类数据拉取失败", err);
      } finally {
        setLoading(false);
      }
    };
    getCats();
  }, []);

  return(
    <div>
      <Autocomplete
        multiple
        id="tags-standard"
        loading={loading}
        options={categories}
        // 空值兜底
        getOptionLabel={(c) => c?.name || ""}
        // 选项存在时才设置默认值
        defaultValue={categories[3] ? [categories[3]] : []}
        renderInput={(params) => (
          <TextField
            {...params}
            variant="standard"
            label="Multiple values"
            placeholder="Favorites"
          />
        )}
      />
    </div>
  )
}
相关参考截图
  • 报错截图:报错截图
  • MongoDB分类数据存储截图:MongoDB数据截图

内容的提问来源于stack exchange,提问作者sultan.h

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 22:15:49