空指针 Dereference
快速摘要
你 tried 到读取属性 or call 方法 on 空 or undefined — 值有 否属性到 access.
为什么发生
函数 returned 空 unexpectedly
对象是 不 initialized 之前 use
属性 access 链 hit 空中级值
最小示例
✗ 错误代码
const user = null;
console.log(user.profile.name); // TypeError!✓ 修复代码
const user = null;
console.log(user?.profile?.name ?? 'Unknown'); // 'Unknown'用户是 空, 所以 accessing 用户.profile throws TypeError. 可选 chaining (?.) 返回 undefined 相反的 throwing, and ?? provides fallback 值.
如何诊断
读取错误消息 — 它 names 属性那个失败
Log 值之前属性 access 到确认它 是空
Trace 哪里空 值 came 从
如何修复
添加空 检查之前 accessing 属性
Use 可选 chaining (?.) 到 safely access nested 属性
Provide 默认值 使用 nullish coalescing 运算符 (??)
如何预防
Use 可选 chaining consistently for uncertain 值
Initialize 变量使用默认对象相反的 空