Node.js报TypeError: Cannot read property 'variable' of undefined如何防崩溃
错误根因
- 报错
TypeError: Cannot read property 'notification' of undefined的核心原因是**sockets[index]本身为undefined**,而非sockets[index].notification未定义。原有判断逻辑直接访问sockets[index].notification的类型,当sockets[index]不存在时,访问操作本身就会直接抛出错误,无法进入判断分支。
正确处理方案
方案1:逐层判空(兼容所有Node.js版本)
先校验上层对象存在,再操作下层属性:
// 仅需保证sockets[index]存在就赋值的场景 if (sockets[index] != null) { sockets[index].notification = 1; }
如果需要同时校验notification属性已存在再赋值,扩展为:
if (sockets[index] != null && typeof sockets[index].notification !== 'undefined') { sockets[index].notification = 1; }
注:!= null的写法可以同时排除undefined和null两种空值场景,代码更简洁。
方案2:可选链语法(Node.js v14.0.0及以上版本支持)
使用可选链运算符?.简化多层判空逻辑,遇到空值时会直接短路返回,不会抛出错误:
// 多层校验简化写法 if (typeof sockets?.[index]?.notification !== 'undefined') { sockets[index].notification = 1; }
如果仅需校验sockets[index]存在,还可以直接简化为:
sockets?.[index] && (sockets[index].notification = 1);
方案3:异常兜底
如果希望完全避免该段逻辑影响整体程序运行,可以用try-catch块包裹,同时可添加日志方便后续定位问题:
try { sockets[index].notification = 1; } catch (err) { console.error('notification赋值失败', err); }
内容的提问来源于stack exchange,提问作者mynameisbutt
相关产品推荐
相关产品推荐

