React交易应用运行报错Cannot read properties of undefined (reading 'reduce')
问题现象
- 交易类应用运行时持续抛出
Cannot read properties of undefined (reading 'reduce')错误 - 应用无法正常启动,页面直接渲染为白屏
- 故障为突发,此前应用运行无任何异常
- 报错截图如下:

关联代码
Summary组件 index.tsx
import React, {useContext} from 'react' import incomeImg from '../../assets/income.svg' import outcomeImg from '../../assets/outcome.svg' import totalImg from '../../assets/total.svg' import { useTransactions } from '../../hooks/useTransactions' import { Container } from './styles' export function Summary() { const {transactions} = useTransactions() const summary = transactions.reduce((acc,transaction)=>{ if (transaction.type === 'deposit'){ acc.deposit += transaction.amount acc.total += transaction.amount } else { acc.withdraw = transaction.amount acc.total -= transaction.amount } return acc }, { deposit: 0, withdraw: 0, total: 0 }) return (/* 页面渲染逻辑 */)
useTransactions 自定义Hook
该Hook通过React Context向业务组件下发交易数据,transactions字段为交易列表,数据通过接口异步拉取获取。
根因分析
- 直接报错原因:组件首次渲染时,
useTransactions返回的transactions值为undefined。
异步拉取交易数据需要耗时,若Context的初始值未给transactions设置空数组默认值,组件首次挂载时拿到的就是undefined,此时直接调用数组实例方法reduce会触发类型错误,导致整个组件树渲染崩溃,出现白屏。此前运行正常大概率是本地有缓存、接口响应速度极快,没有触发首次渲染的空值边界场景,本次因为缓存失效、接口延迟等原因暴露了问题。 - 隐藏逻辑缺陷:统计金额的
reduce回调中,支出(withdraw)的计算错误使用了赋值操作符=,会导致最终统计的支出总额等于最后一笔支出的金额,收入支出总览数据计算错误。
修复方法
- 给
transactions添加空值兜底,保证执行reduce时操作的始终是数组:
解构Hook返回值时设置默认空数组即可:
更推荐的做法是在创建TransactionContext时,就给const { transactions = [] } = useTransactions()transactions设置初始值[],从源头避免所有消费组件拿到undefined。 - 修复支出统计的逻辑错误,将赋值改为累加:
const summary = transactions.reduce((acc,transaction)=>{ if (transaction.type === 'deposit'){ acc.deposit += transaction.amount acc.total += transaction.amount } else { // 原代码为 = 直接赋值,改为 += 累加所有支出金额 acc.withdraw += transaction.amount acc.total -= transaction.amount } return acc }, { deposit: 0, withdraw: 0, total: 0 })
内容的提问来源于stack exchange,提问作者gabrielforster
相关产品推荐
相关产品推荐

