【typescript】 action(fn) 中 this
`import { configure, observable, action } from 'mobx-miniprogram';
// 不允许在动作外部修改状态 configure({ enforceActions: 'observed' });
export const store = observable({ /** 数据字段 */ numA: 1, numB: 2,
/** 计算属性 */
get sum() {
return this.numA + this.numB;
},
/** actions */
update: action(function() {
const sum = this.sum;
this.numA = this.numB;
this.numB = sum;
}),
setNumA: action(function(num) {
this.numA = num;
})
}); ` 这里action(fn),中fn的this 怎么解决,现在会error:'this' implicitly has type 'any' because it does not have a type annotation.ts(2683) store.ts(17, 20): An outer value of 'this' is shadowed by this container. View Problem (⌥F8) No quick fixes available
使用 runInAction
update: function() { runInAction(() => { const sum = this.sum }) }
使用 runInAction
update: function() { runInAction(() => { const sum = this.sum }) }
如果需要同步更新的话,runInAction不满足需求啊。
同问,我都是直接不使用action的,直接定义方法,然后再store.methodName(),好像也没有什么问题
这个看起来是 mobx 自身的问题,目前可以自己 hack 下他的类型,binding 这边我看看有没有办法处理下。
直接store.methodName()确实没问题,先就这样用吧。
除了直接store.methodName(),有什么解决方案了,目前可以运行但是类型校验报错"this" 隐式具有类型 "any",因为它没有类型注释。ts(2683)
这个this类型有解决办法吗
可以手动跟“this”指定类型,如下:
interface Data {
numA: number
numB: number
get sum(): number
}
update: action(function(this: Data) {
const sum = this.sum
this.numA = this.numB
this.numB = sum
})