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

MERN项目React-Redux调用state时报错:DefaultRootState不存在对应属性

报错原因

该错误为TypeScript类型校验报错,react-redux默认提供的DefaultRootState为空类型,未包含你在Redux store中自定义的productList、productDetails、cart等状态字段,因此无法识别对应属性。

解决方案

根据你的项目技术选型可选择以下任意一种方案:

方案1:TS项目全局类型配置(长期推荐)

  1. 在Redux store配置文件中导出全局状态类型:
// 你的store配置文件(store.ts 或 store.js)
import { configureStore } from '@reduxjs/toolkit'
// 引入你所有的reducer
import productListReducer from './reducers/productListReducer'
import productDetailsReducer from './reducers/productDetailsReducer'
import cartReducer from './reducers/cartReducer'

export const store = configureStore({
  reducer: {
    // 确认这里注册的key和你调用时取的字段名完全一致
    productList: productListReducer,
    productDetails: productDetailsReducer,
    cart: cartReducer
  }
})

// 导出全局RootState类型
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
  1. 全局覆盖react-redux的默认RootState类型,新建src/types/react-redux.d.ts类型声明文件,写入以下内容:
import 'react-redux'
import type { RootState } from '../store'

declare module 'react-redux' {
  interface DefaultRootState extends RootState {}
}

配置完成后重启TS服务即可消除所有同类报错。

方案2:调用时临时指定类型

不需要修改全局配置,只需要在每次调用useSelector时手动指定state类型即可:

import type { RootState } from './store'

// 调用时指定state类型
const productList = useSelector((state: RootState) => state.productList)

方案3:纯JS项目关闭校验

如果你的项目是纯JavaScript项目,不需要TS校验,可以直接关闭JS文件的类型检查:

  • 方式1:在报错代码行上方添加// @ts-ignore注释,忽略单条报错
  • 方式2:在项目根目录的jsconfig.json中添加"checkJs": false,关闭所有JS文件的TS校验
  • 方式3:修改VS Code设置,搜索checkJs,关闭JavaScript > Implicit Project Config: Check JS选项
注意事项

需要先确认你在store的reducer配置项中,已经正确注册了对应字段的reducer,且key的拼写和你useSelector中取的字段名完全一致,否则即使类型校验通过,运行时也无法取到对应状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:54:00