我是mobx-state-tree
第一次使用,我试图用它types.model
来建模一个泛型类型。我正在尝试使用这个现有的 mobx 代码:
/**
* Models an Async request / response - all the properties exposed are
* decorated with `observable.ref`; i.e. they are immutable
*/
class Async<TRequest, TResponse> implements IAsyncProps<TResponse> {
/**
* Whether a request is in process
*/
@observable.ref isRequesting: boolean = false;
/**
* (optional) The response received last time a request was run
*/
@observable.ref response?: TResponse;
/**
* (optional) The error received last time a request was run
*/
@observable.ref error?: string;
constructor(private process: (request: TRequest) => Promise<TResponse>) {
}
@action
async run(request?: TRequest) {
try {
this.isRequesting = true;
this.response = undefined;
this.error = undefined;
const response = await this.process(request);
this.runSuccess(response);
} catch (error) {
this.runError(error);
}
}
@action private runSuccess(response: TResponse) {
this.response = response;
this.isRequesting = false;
}
@action private runError(error: any) {
this.error = error.message ? error.message : error;
this.isRequesting = false;
}
@action
reset() {
this.isRequesting = false;
this.response = undefined;
this.error = undefined;
return this;
}
}
我想将它移植到types.model
. 我已经做到了这一点:
const Async2 = types.model('Async2', {
isRequesting: types.boolean,
response: types.optional(/*types.? what goes here ???*/, undefined),
error: types.optional(types.string, undefined)
});
但我坚持如何一般地输入响应。我可以处理其余的操作 - 有人知道这是否可能吗?