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

Mobx框架下Observer与Computed无法随Reaction更新的问题

问题分析

你的代码里有个核心问题:_setupValidations里的reaction完全是多余的——它会在_selectedCountryIndex变化时,再次调用setSelectedCountryIndex把值设成当前的_selectedCountryIndex,这种无意义的重复操作会干扰Mobx的响应式状态追踪逻辑,直接导致Observer无法正确感知Computed属性的变化。

另外,selectedCountryIndexInt这个Computed属性只是直接返回Observable变量的值,没有任何额外计算逻辑,完全可以简化成普通getter,避免不必要的Computed开销(这不是核心问题,但能优化代码)。

解决方案

1. 移除干扰性的Reaction

直接删掉那个无意义的reaction,以及相关的初始化和销毁逻辑:

// 删掉整个_setupValidations方法,以及构造函数里的调用
// 同时删掉_disposers变量和dispose方法里的循环逻辑

2. 简化冗余的Computed属性(可选)

把selectedCountryIndexInt从Computed改成普通getter,因为它没有计算逻辑:

@observable
int _selectedCountryIndex = 0;

// 替换原来的@computed getter
int get selectedCountryIndexInt => _selectedCountryIndex;

selectedCountryCode这个Computed是有实际计算逻辑的(拼接字符串),可以保留。

3. 确保Store实例唯一

确认你的injector提供的AuthStore是单例实例,避免Observer每次获取不同的Store对象,导致状态变化无法被追踪。

修改后的完整AuthStore代码
import 'package:mobx/mobx.dart';

part 'auth_store.g.dart';
class AuthStore = AuthStoreBase with _$AuthStore;

abstract class AuthStoreBase with Store {
  @observable
  int _selectedCountryIndex = 0;

  int get selectedCountryIndexInt => _selectedCountryIndex;

  @action
  void setSelectedCountryIndex(int val) {
    _selectedCountryIndex = val;
  }

  @computed
  String get selectedCountryCode => "+$_selectedCountryIndex";
}
验证步骤

修改后重新运行代码生成命令:

flutter pub run build_runner build

之后点击UI中的文本,就能看到selectedCountryCode和selectedCountryIndexInt实时更新,Observer会自动响应状态变化,不需要手动调用setState或触发生命周期更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 06:54:55