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

Mobx无法更新React Native组件问题求助

问题原因

每次App组件渲染时,都会重新执行const counterStore = new CounterStore(0);,创建一个全新的CounterStore实例。点击按钮时,确实修改了当前实例的count值(所以日志能看到数值增长),但组件触发重新渲染后,又会生成一个初始值为0的新实例,导致UI始终显示0。

解决方案

需要让CounterStore实例在组件生命周期内保持唯一,避免每次渲染都重新创建。以下两种简单方案都可以实现:

方法1:使用useRef持久化实例

修改index.tsx中的App组件:

import { observer } from "mobx-react";
import React, { useRef } from "react";
import { Button, StyleSheet, Text, View } from "react-native";
import CounterStore from './stores/CounterStore';

export function App() {
  // 用useRef存储store实例,仅在组件首次渲染时初始化一次
  const counterStoreRef = useRef(new CounterStore(0));
  const counterStore = counterStoreRef.current;

  return (
    <View style={styles.container}>
      <View style={styles.wrapper}>
        <Text>{counterStore.count}</Text>
        <Button
          title="Add"
          onPress={() => {
            counterStore.addToCount();
            console.log("count = ", counterStore.count);
          }}
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    height: "100%"
  },
  wrapper: {
    backgroundColor: "#F5FCFF",
    width: "100%",
    maxWidth: 425
  }
});

export default observer(App);

方法2:使用useState单次初始化

import { observer } from "mobx-react";
import React, { useState } from "react";
import { Button, StyleSheet, Text, View } from "react-native";
import CounterStore from './stores/CounterStore';

export function App() {
  // 传入初始化函数给useState,仅在组件首次渲染时执行
  const [counterStore] = useState(() => new CounterStore(0));

  return (
    <View style={styles.container}>
      <View style={styles.wrapper}>
        <Text>{counterStore.count}</Text>
        <Button
          title="Add"
          onPress={() => {
            counterStore.addToCount();
            console.log("count = ", counterStore.count);
          }}
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    height: "100%"
  },
  wrapper: {
    backgroundColor: "#F5FCFF",
    width: "100%",
    maxWidth: 425
  }
});

export default observer(App);
额外说明

你已经正确用observer包裹了App组件,它能响应Mobx observable的变化,只要store实例保持持久化,UI就能正常跟随count值更新。如果是大型应用,也可以通过React Context全局注入store,避免在多个组件中重复初始化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:51:17