我正在尝试从存储库中获取数据,但是在尝试调用api时出现错误,这是我的商店:
class Locations = _Locations with _$Locations;
abstract class _Locations implements Store {
ApiClient _apiClient;
_Locations(ApiClient apiClient){
_apiClient = apiClient;
}
@observable
List<Location>locations = [];
@action
Future<List<Location>> fetchLocations() async{
locations = await apiClient.getLocations();
}
}
错误输出是..
[SEVERE] mobx_codegen|mobx_generator on lib/ui/location/state/locations.dart:
Could not make class "Locations" observable. Changes needed:
1. Remove async modifier from the method "fetchLocations"
知道我在做什么错吗?
答案 0 :(得分:1)
使用runInAction
来改变状态,并使用常规的异步函数来获取数据
void fetchLocations async() {
locationsList = await apiClient.getLocations();
runInAction(() => locations = locationsList);
}
答案 1 :(得分:1)
您还可以从操作代码(仅修改可观察对象)中拆分异步代码:
@observable
ObservableList<Location> locations = [];
void fetchLocations() async {
final locations = await _apiClient.getLocations();
addLocations(locations);
}
@action
void addLocations(List<Location> newLocations) {
locations.addAll(newLocations);
}
即使您没有从用户界面调用操作,上述操作也将起作用。
答案 2 :(得分:1)
MobX.dart现在支持异步操作。只要确保返回一个Future
。它将自动将所有突变包装在一个动作中!
@observable
ObservableList<Location> locations = [];
@action
Future<void> fetchLocations() async {
final locations = await _apiClient.getLocations();
locations.addAll(newLocations); // this will be wrapped inside an action
}