wechat-miniprogram / mobx-miniprogram-bindings

小程序的 MobX 绑定辅助库
MIT License
206 stars 20 forks source link

【typescript】 action(fn) 中 this #18

Closed iamAzure closed 4 months ago

iamAzure commented 3 years ago

`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

feralclaw commented 3 years ago

使用 runInAction

update: function() { runInAction(() => { const sum = this.sum }) }

ChaneyZhao commented 2 years ago

使用 runInAction

update: function() { runInAction(() => { const sum = this.sum }) }

如果需要同步更新的话,runInAction不满足需求啊。

zenonux commented 2 years ago

同问,我都是直接不使用action的,直接定义方法,然后再store.methodName(),好像也没有什么问题

TtTRz commented 2 years ago

这个看起来是 mobx 自身的问题,目前可以自己 hack 下他的类型,binding 这边我看看有没有办法处理下。

ChaneyZhao commented 2 years ago

直接store.methodName()确实没问题,先就这样用吧。

Aliom252181 commented 2 years ago

除了直接store.methodName(),有什么解决方案了,目前可以运行但是类型校验报错"this" 隐式具有类型 "any",因为它没有类型注释。ts(2683)

Nice-PLQ commented 1 year ago

这个this类型有解决办法吗

lei1248276 commented 1 year ago

可以手动跟“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
})