You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React电商项目本地运行报Cannot read 'source' of undefined错误如何解决

问题原因

报错TypeError: Cannot read properties of undefined (reading 'source')指向Product.jsx里的product.media.source取值逻辑,触发原因是product.media为undefined,尝试读取undefined的source属性就会抛出该错误。
导致该问题的常见场景有两个:

  • 调用commerce商品接口请求失败,setProducts未被正确赋值,或者接口返回的部分商品数据缺失media字段
  • 没有做字段兼容处理,只要单条商品数据结构不符合预期,就会导致整页渲染崩溃

修复步骤

1. 增加接口异常捕获和日志排查

修改App.js中的fetchProducts方法,先确认接口返回是否正常:

const fetchProducts = async () => {
  try {
    const { data } = await commerce.products.list();
    // 打印返回数据,确认每条商品的media字段是否存在
    console.log('商品接口返回数据:', data);
    setProducts(data);
  } catch (err) {
    // 捕获请求异常,排查接口调用失败原因
    console.error('商品列表请求失败:', err);
  }
}

2. 新增字段兼容处理

修改Product.jsx中的取值逻辑,用可选链+默认值兜底,避免字段缺失导致崩溃:

// CardMedia部分修改为
<CardMedia 
  className={classes.media} 
  image={product.media?.source || ''} 
  title={product.name || '商品'}
/>

// 价格取值也可以同步加兼容,避免后续报错
<Typography variant="h5">
  {product.price?.formatted_with_symbol || '¥ 0.00'}
</Typography>

3. 新增加载状态(可选,优化体验)

可以在App.js中新增加载状态,接口请求完成前不渲染商品列表,避免不必要的渲染异常:

// 新增loading状态
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);

const fetchProducts = async () => {
  try {
    const { data } = await commerce.products.list();
    setProducts(data);
  } catch (err) {
    console.error('商品列表请求失败:', err);
  } finally {
    setLoading(false);
  }
}

// 渲染逻辑修改
return (
  <div>
    <Navbar />
    {loading ? <div>商品加载中...</div> : <Products products={products} />}
  </div>
)

内容的提问来源于stack exchange,提问作者ctrizzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:36:04