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

Nuxtjs/Vuejs购物车计算时报Cannot read properties of undefined (reading 'reduce')错误

问题原因

你代码的核心错误有3处:

  • 语句return sum ? ...中的sum没有加this前缀,直接访问会抛出「变量未定义」的报错
  • 计算属性内部修改data声明的响应式变量sum属于错误用法,会触发重复渲染,极端情况会出现更新死循环
  • 没有处理lineItems未加载的边界场景,当store中checkout数据还未初始化时,lineItems为undefined,调用reduce方法会直接报错

修正后代码

<script>
export default {
  name: 'CartIcon',
  computed: {
    count() {
      // 新增容错处理,避免数据未加载时报错
      const lineItems = this.$store.getters["checkout/checkout"]?.lineItems || []
      const totalCount = lineItems.reduce((accumulator, item) => accumulator + item.quantity, 0)
      return totalCount >= 99 ? "99+" : totalCount
    }
  }
}
</script>

调整说明

  • 移除了冗余的sum响应式变量,计算属性本身即可缓存计算结果,不需要额外用data存储中间值
  • 新增可选链和默认空数组的容错逻辑,数据加载过程中也不会触发报错
  • 简化了返回值判断逻辑,reduce的初始值为0,不需要额外判断假值再返回0

内容的提问来源于stack exchange,提问作者marion.serenio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:15:06