React+Mobx开发报错:Cannot read property 'map' of undefined 问题排查
目标实现功能
- 从API拉取数据存入名为
UserStore的Mobx仓库 - 在其他组件中读取
UserStore存储的数据完成页面展示
各文件现有代码实现
UserStore.ts 仓库定义
import { observable, action } from 'mobx'; import { getUser } from '../api/api'; export class UserStore { @observable users: [{ firstName: string; surName: string; dateofBirth: string; ethnicity: string, maritalStatus: string, }] @action loadUser = () => { getUser().then(users => this.users = users) console.log(this.users) } }
API 请求配置
后端API为独立运行在Visual Studio中的项目,已通过Postman验证接口可用性,可正常返回200状态响应。
export const getUser = ():Promise<[{ firstName: string; surName: string; dateofBirth: string; ethnicity: string; maritalStatus: string; }]> => { return fetch('https://localhost:5001/api/personalInfo/1').then(res => res.json()) }
全局状态上下文配置
用于在项目任意位置访问全局状态仓库
import React from 'react'; import { UserStore } from '../stores/UserStore'; type RootStateContextValue = { userStore: UserStore; }; const RootStateContext = React.createContext<RootStateContextValue>({} as RootStateContextValue); const userStore = new UserStore(); export const RootStateProvider: React.FC<React.PropsWithChildren<{}>> = ({ children }) => { return <RootStateContext.Provider value={{ userStore }}> {children} </RootStateContext.Provider>; }; export const useRootStore = () => React.useContext(RootStateContext);
入口文件 index.tsx 配置
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import reportWebVitals from './reportWebVitals'; import App from './App'; import { RootStateProvider } from './context/RootStateContext'; import './css/main.css'; ReactDOM.render( <BrowserRouter basename={'myCareer'}> <RootStateProvider> <App /> </RootStateProvider> </BrowserRouter>, document.getElementById('root'), );
业务展示组件 PersonalInformation_Card.tsx
尝试遍历UserStore存储的数据完成页面渲染
export default function PersonalInformation_Paper() { const { userStore } = useRootStore(); return useObserver(() => ( <> <div> {userStore.users.map((user) => { return ( <option key={user.firstName} value={user.firstName}> {user.firstName} </option> ); })} </div> </> )); }
报错与排查过程
当前页面持续触发报错:TypeError: Cannot read property 'map' of undefined
初步判断问题由API请求未执行、仓库未有效填充数据导致无内容可遍历,但无法确认问题根源,需要获取相关排查指导。
补充排查记录:
- 未调整状态初始值时,控制台输出的userStore内容:

- 调整可观察属性为带空字段初始值的数组后的代码变更与对应控制台输出:
原声明代码:
调整后的代码:@observable users: [{ firstName: string; surName: string; dateofBirth: string; ethnicity: string, maritalStatus: string, }]
调整后的控制台输出截图:@observable users = [{ firstName: '', surName: '', dateofBirth: '', ethnicity: '', maritalStatus: '', }]
内容的提问来源于stack exchange,提问作者MD9
相关产品推荐
相关产品推荐

