Next.js部署至Vercel时出现TypeError: 无法读取undefined的'name'属性
解决TypeError: Cannot read properties of undefined (reading 'name')
问题根源分析
你遇到的错误并非来自newNodeName,而是以下两个核心问题:
- 未正确处理
tree参数的数组类型:代码直接将tree强制转为单个RawNodeDatum,如果传入的是数组,队列中会混入数组元素,访问curNode.name自然报错(数组没有name属性)。 - 过度依赖非空断言
!:忽略了curNode、curNode.children可能为undefined的情况,一旦实际数据中存在无children的节点,就会触发属性读取错误。
修复步骤及代码优化
1. 正确处理tree的数组类型
先判断tree是单个节点还是数组,将所有节点加入队列:
// 替换原队列初始化代码 const queue: RawNodeDatum[] = []; if (Array.isArray(nodeBFSInterface.tree)) { queue.unshift(...nodeBFSInterface.tree); } else { queue.unshift(nodeBFSInterface.tree); }
2. 移除危险断言,添加空值检查
在访问节点属性前先做存在性校验,操作children前确保其存在(不存在则初始化空数组):
while (queue.length > 0) { const curNode = queue.pop(); // 跳过空节点 if (!curNode) continue; if ( curNode.name === nodeBFSInterface.name && nodeBFSInterface.attributes?.type === 'landerRotator' ) { // 确保children存在,不存在则初始化为空数组 const children = curNode.children ?? []; children.push({ name: nodeBFSInterface.newNodeName ?? '', attributes: { type: nodeBFSInterface.attributes.type }, children: [], }); curNode.children = children; return { ...nodeBFSInterface.tree }; } else if ( curNode.name === nodeBFSInterface.name && nodeBFSInterface.attributes?.type === 'landerParent' ) { const children = curNode.children ?? []; children.push({ name: nodeBFSInterface.newNodeName ?? '', attributes: { type: nodeBFSInterface.attributes.type, url: nodeBFSInterface.attributes.url ?? '', weight: nodeBFSInterface.attributes.weight ?? undefined, }, children: [], }); curNode.children = children; return { ...nodeBFSInterface.tree }; } // 处理子节点前先检查是否存在 const children = curNode.children ?? []; for (const child of children) { queue.unshift(child); } }
3. 简化空值判断逻辑
用TypeScript的空值合并运算符??替代三元表达式,语义更清晰:
nodeBFSInterface.newNodeName ?? '':当newNodeName为undefined或null时,使用空字符串curNode.children ?? []:当children不存在时,使用空数组
额外优化建议
- 给
newNodeName设置默认值,避免传入空值:
function nodeBFS({ newNodeName = '', ...rest }: nodeBFSInterface) { // 后续直接使用newNodeName即可 }
- 尽量避免非空断言
!:除非你100%确定变量不会为空,否则优先用可选链?.或空值检查。
内容的提问来源于stack exchange,提问作者jeril
相关产品推荐
相关产品推荐

