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

如何使用Mobx为FlatList设置数据?收藏页列表显示为空是什么原因?

问题原因及修复方案
  • 问题1:listData方法仅定义未执行
    你在bookMarkList方法内声明了listData箭头函数,但没有触发调用,导致bookmarkApi接口请求从未发起,petList一直保持初始空数组状态,FlatList无数据可渲染。
  • 问题2:请求回调this指向丢失
    就算调用listData,你给then传入的是普通函数function (responseJson),普通函数的this不指向Favorites类实例,会导致this.petList、this.userId读取报错,也无法给store的petList赋值。你之前遇到的_this2.userId报错就是this指向丢失导致的。
  • 问题3:listData未声明变量
    直接写listData = () => {}没有加const/let变量声明,严格模式下会抛出全局变量赋值报错。
修复后的代码

修正后的favorites store代码

import { observable, action, makeObservable, configure } from "mobx";
import { bookmarkApi } from '../../constants/apiURL';
import AsyncStorage from '@react-native-async-storage/async-storage';

configure({
    enforceActions: "never",
})

class Favorites {
    userId = 0;
    petList = [];

    constructor() {
        this.bookMarkList()
        makeObservable(this, {
            userId: observable,
            petList: observable,
            bookMarkList: action,
        })
    }

    bookMarkList = async () => {
        const value = await AsyncStorage.getItem('userId')
        if (value == null) return
        this.userId = value;
        // 直接发起请求,用async/await保留this指向
        const res = await bookmarkApi.get('/')
        if (res) {
            this.petList = res.data.filter(data => data.userId == this.userId)
        }
    }
}

export const favoriteStore = new Favorites();

这里把原来的.then链式调用换成了async/await写法,逻辑更清晰,也天然保留了外层bookMarkList箭头函数的this指向,不会出现this读取undefined的问题。

FavoriteScreen.js 代码无问题

你已经用observer包裹了组件,会自动响应petList的 observable 变化,store修复后FlatList就能正常渲染数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:45:05