修复Shopify购后脚本Cannot read properties of undefined (reading 'product')报错
报错修复方案
错误根因
window.Shopify.order.lineitem 是数组类型,存储当前订单的所有商品条目,而非单个商品对象,直接访问数组的product属性会返回undefined,触发类型错误。
修复后完整代码
// 购物车变量 var cartTagsString = ""; var cartProductIDString = ""; // 遍历订单商品数组 window.Shopify.order.lineitem.forEach(function (lineItem) { // 安全获取商品对象 const product = lineItem?.product; if (!product) return; // 拼接商品标签 if (Array.isArray(product.tags)) { product.tags.forEach(function (tag) { cartTagsString += tag; }); } // 拼接商品ID if (product.id) { cartProductIDString += product.id; } });
补充说明
- 代码中使用了可选链
?.做属性安全访问,若需要兼容低版本运行环境,可替换为多层if属性存在性判断 - 若需要在多个标签/ID之间添加分隔符,可在拼接逻辑中插入对应字符,例如需要逗号分隔时修改为
cartTagsString += tag + ','即可 - 原代码第二个循环存在逻辑错误,误将商品标签字符串拼接到商品ID字符串中,上述修复代码已修正该问题
内容的提问来源于stack exchange,提问作者Jack Trowbridge
相关产品推荐
相关产品推荐

