Skip to content

TypeError: Cannot 读取属性的 undefined

错误信息

                Cannot 读取属性的 undefined (读取 'x')
              

快速摘要

你 used 点 notation on 值那个是 `undefined` — 属性 doesn't exist 因为对象它自己是 missing.

为什么发生

  • 对象是 从不 assigned or 是设置到 undefined

  • 函数 returned undefined and caller accessed 属性 on result

  • 数组元素 or nested 属性是 undefined (e.g., 用户.地址.city 当 地址 是 undefined)

最小示例

✗ 错误代码
let user;
console.log(user.name);
✓ 修复代码
let user;
console.log(user?.name);

用户 是 undefined, 所以 accessing .name throws TypeError — 可选 chaining (?.) 返回 undefined 相反的 throwing.

如何诊断

  • Log 对象正确之前属性 access 到确认它 是 undefined

  • Trace 哪里对象应该有 是 assigned or returned

  • 检查 API 响应 for missing 字段那个 lead 到 undefined

如何修复

  • 添加 guard 检查之前 accessing 属性 (如果 (obj))

  • Use 可选 chaining (obj?.属性) 到 safely access nested 属性

  • Provide 默认对象所以属性总是 exists

如何预防

  • Use 可选 chaining (?.) for 所有 uncertain 属性 accesses

  • 验证 API 响应之前 using 它们

相关资源

相关术语

相关课程

  • 对象

    学习如何 JavaScript 对象工作

相关练习

← 返回语言