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

使用createSlice时amount读取为undefined的问题排查

问题分析与解决

错误Cannot read properties of undefined (reading 'amount')的核心原因是:你的reducer中尝试读取payload.amount,但dispatch时传递的action未正确包含payload字段,导致payload为undefined,进而无法读取amount属性。

修复方案

有两种规范的修复方式,推荐使用第一种:


方式一:使用Redux Toolkit自动生成的Action Creators(推荐)

Redux Toolkit的createSlice已经为你生成了对应的action创建函数(deposit、withdrawal、transfer),直接调用这些函数可以避免手动构造action的格式错误。

  1. 在Transactions.jsx中导入这些action创建函数:
import { deposit, withdrawal, transfer } from '../features/transactions/transactionsSlice';
  1. 修改onTransaction函数的dispatch逻辑,根据按钮的action值匹配对应的action创建函数:
const onTransaction = (e) => {
  e.preventDefault();
  const action = e.nativeEvent.submitter.name;
  const amount = +amountStr;

  // 根据按钮类型分发对应action
  switch(action) {
    case 'deposit':
      dispatch(deposit({ amount }));
      break;
    case 'withdraw':
      // 注意按钮name是withdraw,对应slice里的withdrawal action
      dispatch(withdrawal({ amount }));
      break;
    case 'transfer':
      dispatch(transfer({ amount }));
      break;
    default:
      break;
  }
};

方式二:手动构造符合格式的Action

如果要手动编写action对象,必须将数据放在payload字段中,匹配reducer的读取逻辑:

const onTransaction = (e) => {
  e.preventDefault();
  const action = e.nativeEvent.submitter.name;
  const amount = +amountStr;

  // 手动构造action时,将amount放入payload对象
  const actionType = action === 'withdraw' ? 'withdrawal' : action;
  dispatch({
    type: `transactions/${actionType}`,
    payload: { amount }
  });
};

原理说明

你的slice中所有reducer(比如deposit)都是从payload.amount读取数值的:

deposit: (state, { payload }) => {
  state.balance += payload.amount;
  // ...
}

无论用哪种方式,只要确保dispatch的action包含payload字段,且payload内有amount属性,就能让reducer正确读取数值,解决报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 00:43:14