嵌套forEach中if语句引发TypeError: Cannot read properties of undefined问题排查
问题分析与解决
错误根源
匹配失败导致
matchingProduct为undefined
你购物车项的productId(156a1ze6-985s-78aze-5646q5sd-aze5q6s214ggh)和产品列表里的所有id都不匹配,所以内层forEach里的if (product.id === productId)条件从未触发,matchingProduct始终保持初始的undefined状态。如果后续代码尝试访问它的属性(比如matchingProduct.priceCents),就会抛出TypeError: Cannot read properties of undefined错误。昨天正常工作的原因
大概率是昨天购物车数据中的productId是正确的,能和产品列表里的某个id匹配,今天可能误修改了购物车的productId,或者产品列表的id发生了变更,导致匹配失效。
修复方案
1. 修正购物车的productId
确保购物车项的productId和产品列表里的有效id一致,比如改成篮球产品的id:
const cart = [{ productId: "15b6fc6f-327a-4ec4-896f-486349e85a3d", quantity: 2, }];
2. 优化代码逻辑(更健壮)
用Array.find()替代嵌套forEach,代码更简洁,还能直接处理未找到产品的情况,避免后续报错:
const cart = [{ productId: "156a1ze6-985s-78aze-5646q5sd-aze5q6s214ggh", quantity: 2, }]; cart.forEach((cartItem) => { const matchingProduct = products.find(product => product.id === cartItem.productId); // 先判断是否找到产品,再进行后续操作 if (matchingProduct) { console.log(matchingProduct); // 这里可以放心访问matchingProduct的属性,比如matchingProduct.priceCents } else { console.log(`未找到id为${cartItem.productId}的产品`); } });
内容的提问来源于stack exchange,提问作者Massinissaa Ouiddir
相关产品推荐
相关产品推荐

