Mobx 传递回调以更新进度不允许我实时更新可观察到的

Mobx passing callback to update progress not letting me update observable in real time

我有一个函数可以将一个对象放入 Firebase 存储中。这个函数接受一个回调,让我返回进度,以便我可以跟踪它。我想将此进度存储在一个可观察对象中,但是当我尝试通过回调更新可观察对象时,我收到错误消息,指出我的可观察对象未定义。这是一个剥离的例子:

function putThingInFirebase(thing, cb) {
  // ...
  const videoUploadTask = videoStorageRef.put(thing)
  videoUploadTask.on('state_changed', snap => {
  let progress = (snap.bytesTransferred / snap.totalBytes) * 100
  cb(Math.round(progress)) // callback from my store
  // handle errors and such
  // ....


// my store
class store {
  @observable progress
  @action upload(thing) {
     putThingInFirebase(thing, this.progressCB)
        .then(...)
  }
  progressCB(x) { // ive tried @action and @action.bound
    this.progress = x // here i get errors that this.progress is undefined yet when i do a console.log, x is being updated as expected
  }
}

我期望发生的是通过回调更新可观察对象。 我得到的是 this.progress 未定义。

我的问题是:更新此 observable 以便我可以监控上传进度的正确方法是什么?

感谢大家的宝贵时间和帮助!

编辑:乔尔是正确的。请参阅下面我的评论,了解真正的罪魁祸首!

关于使用承诺中的解决方案的建议,不幸的是我需要访问“state_changed”侦听器,这在 .then() 中是不可能的。

您正在失去 this

的上下文

当您调用 cb() 时,会调用 progressCB() 但在此函数中 this 不是商店实例。

尝试:

putThingInFirebase(thing, this.progressCB.bind(this));

//or
putThingInFirebase(thing, (x) => this.progressCB(x));

额外建议

既然你return一个承诺.then()为什么不把这个方法放在那里?而不是 添加回调函数?