React-Redux调用REST API时报TypeError: 无法读取undefined的type属性
TypeError: Cannot read property 'type' of undefined 报错定位与修复 这个报错的本质是Redux store在执行dispatch流程时,收到的action值为undefined,导致内部逻辑读取action.type属性时触发类型错误。结合代码逻辑,问题出在三处核心逻辑错误:
- mapDispatchToProps 绑定逻辑错误(触发该报错的直接原因)
你写的customerbyidGet是一个高阶函数:接收dispatch参数后,返回一个内部包含fetch请求的可执行函数。但你在传给bindActionCreators时,直接执行了customerbyidGet(dispatch),把执行结果(那个发fetch的内部函数)当成了action creator传给bindActionCreators。bindActionCreators的工作逻辑是识别传入的函数,调用后把返回值自动当成action dispatch到store。但你传进去的这个内部函数,执行时只会触发异步fetch流程,本身没有任何返回值(返回值为undefined),bindActionCreators拿到这个undefined值后直接调用dispatch,Redux在处理流程中读取action.type时就抛出了类型错误。
错误写法示例:// Panel.js 原有错误代码 const mapDispatchToProps = dispatch => bindActionCreators({ customerbyidGet: customerbyidGet(dispatch) }, dispatch) - API调用逻辑与action设计脱节
你在fetch的请求发起、成功、失败三个分支里,全部分发了同一个无参数的customerbyidGetAction(),既没有把接口返回的实际数据传入action的payload,也没有区分请求的不同状态,即使修复了绑定报错,Redux里也拿不到实际的接口数据。 - Redux状态结构混用
你在reducer初始化时用fromJS()生成了Immutable格式的不可变状态,但更新状态时却用普通对象的展开语法{...state, data: action.payload}返回普通JS对象,两种格式混用会触发后续状态读取的类型异常。
对应修复步骤
- 修正dispatch绑定逻辑
不需要硬套bindActionCreators,直接在mapDispatchToProps里返回能正确触发API调用的函数即可,参考写法:// Panel.js 修正后的绑定逻辑 const mapDispatchToProps = (dispatch) => ({ // 组件调用customerbyidGet时,自动传入dispatch参数执行API逻辑 customerbyidGet: () => customerbyidGet(dispatch)() }) - 拆分action,匹配API请求的全生命周期
按照请求开始、请求成功、请求失败三个状态分别定义独立的action,把对应的数据传入payload,参考修改后的restApi.js:// restApi.js 修正后逻辑 import { customerbyidGetRequestAction, customerbyidGetSuccessAction, customerbyidGetFailAction } from '../../redux/actions/restActions' export default function customerbyidGet(dispatch) { return () => { // 发送请求开始的action dispatch(customerbyidGetRequestAction()); fetch('https://***.com/api/v1/home', { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'token': 1234 } }) .then(res => res.json()) .then(res => { if(res.error) throw new Error(res.error); // 发送请求成功的action,把接口返回数据传入payload dispatch(customerbyidGetSuccessAction(res)); }) .catch(error => { // 发送请求失败的action,把错误信息传入payload dispatch(customerbyidGetFailAction(error.message)); }) } } - 统一reducer的状态操作语法
如果你项目里用了Immutable.js,就全程用Immutable提供的API读写状态,不要和普通JS对象语法混用,参考修正后的restReducer.js:// restReducer.js 修正后逻辑 import * as types from '../constants/restConstants'; import { fromJS } from 'immutable'; // 用Immutable初始化全量状态 const initialState = fromJS({ data: null, loading: false, error: null }); export default function restReducer(state = initialState, action) { switch(action.type) { case types.customerbyidGetRequestAction: return state.set('loading', true).set('error', null); case types.customerbyidGetSuccessAction: return state.set('loading', false).set('data', fromJS(action.payload)); case types.customerbyidGetFailAction: return state.set('loading', false).set('error', action.payload); default: return state; } }
内容的提问来源于stack exchange,提问作者S.M_Emamian
相关产品推荐
相关产品推荐

