React Native中Axios+MobX获取API数据返回空数组/undefined问题
React Native中Axios+MobX获取API数据为空/undefined的问题
我正在学习在React Native(JS)中使用Axios和MobX,尝试通过这些技术从API获取数据并传递到视图,但始终得到空数组或undefined。
相关代码文件
1. Axios API调用文件
import API from "./api"; export function exampleGroupsAPI() { return API.get('/example-groups').then(response => response.data) }
2. MobX Store文件
import {makeAutoObservable, runInAction} from 'mobx'; import {exampleGroupsAPI} from '../api/agent'; export default class ExampleGroupsStore { exampleGroups = []; loadingInitial = false; constructor() { makeAutoObservable(this); } setLoadingInitial = state => { runInAction(() => { this.loadingInitial = state; }); }; loadExampleGroups = async () => { const result = await exampleGroupsAPI(); runInAction(() => { this.exampleGroups = result.data; }) }; }
3. 数据展示组件
import React, {useEffect} from 'react'; import {Text, StyleSheet} from 'react-native'; import {observer} from 'mobx-react-lite'; import {useExampleGroupsStore} from '../../app/stores/hooks'; const ExampleGroupsList = () => { const { exampleGroups, loadExampleGroups} = useExampleGroupsStore(); useEffect(() => { loadExampleGroups(); }, [loadExampleGroups]); console.log(exampleGroups) return ( <Text> TEST </Text> ); }; export default observer(ExampleGroupsList);
4. Store导出钩子文件
import {StoreContext} from './storeProvider'; export function useExampleGroupsStore() { const store = useContext(StoreContext); return store.ExampleGroupsStore; }
问题分析与修复方案
核心问题:API返回值重复提取.data
在exampleGroupsAPI中,已经通过.then(response => response.data)拿到了接口返回的data部分,但在Store的loadExampleGroups方法里,又再次访问result.data——此时result本身就是接口的data,所以result.data会是undefined,导致最终exampleGroups被赋值为undefined。
修复Store方法
修改loadExampleGroups,直接将result赋值给exampleGroups,同时建议添加加载状态和错误处理:
loadExampleGroups = async () => { this.setLoadingInitial(true); try { const result = await exampleGroupsAPI(); runInAction(() => { // 直接赋值result,无需再取data this.exampleGroups = result; }); } catch (error) { console.error('加载示例组失败:', error); } finally { this.setLoadingInitial(false); } };
组件优化(可选)
可以在组件中加入加载状态展示,避免用户看到空白:
const ExampleGroupsList = () => { const { exampleGroups, loadExampleGroups, loadingInitial} = useExampleGroupsStore(); useEffect(() => { loadExampleGroups(); }, [loadExampleGroups]); if (loadingInitial) { return <Text>加载中...</Text>; } return ( <Text> {exampleGroups.length > 0 ? exampleGroups.map(item => <Text key={item.id}>{item.name}</Text>) : '暂无数据' } </Text> ); };
内容的提问来源于stack exchange,提问作者malikort
相关产品推荐
相关产品推荐

