问题描述
我认为 bind(this)
相当于箭头函数,但是我遇到了一个问题(
这是一个用于跟踪延迟请求的存储。我正在使用orbitjs 库将所有内容保存到IndexedDB 中。它提供了允许订阅数据库更改的 api,所以这里是我的商店:
export class DelayedRequestsstore implements IDelayedRequests {
add = addHttpRequest;
list = queryHttpRequests;
remove = removeHttpRequest;
@observable private _delayedRequestsCount = 0;
@computed get any(): boolean {
return this._delayedRequestsCount > 0;
}
@computed get empty(): boolean {
return !this.any;
}
constructor(db: Sources) {
db.source.on('update',() => {
this._updateDelayedRequestsCount();
});
this._updateDelayedRequestsCount();
}
private async _updateDelayedRequestsCount(): Promise<void> {
const delayedRequests = await this.list();
runInAction(() => {
this._delayedRequestsCount = delayedRequests.length;
});
}
}
constructor(db: Sources) {
db.source.on('update',() => {
this._updateDelayedRequestsCount();
});
this._updateDelayedRequestsCount();
}
还有一些关于反应的代码:
<button onClick={async () => {
await notifyServer();
await clearRequestsFromIndexedDb();
goToAnotherPage();
})>Cancel</button>
constructor(db: Sources) {
db.source.on('update',this._updateDelayedRequestsCount.bind(this));
this._updateDelayedRequestsCount();
}
通过该更改,我没有在控制台中看到任何错误,但 Cancel
按钮不起作用。我已经调试并发现 notifyServer
已被调用,然后 clearRequestsFromIndexedDb
已被调用但 goToAnotherPage
未被调用,就像 clearRequestsFromIndexedDb
中发生错误一样,但没有错误。所以我回滚到箭头功能,一切又正常了。它会影响任何事情吗?或者问题实际上在我遗漏的其他地方?
解决方法
我看到您只将 this
绑定到 db.source.on('update',... )
。但是构造函数中对 this._updateDelayedRequestsCount()
的调用没有绑定。这可能是个问题。
您可以像这样将 this
显式绑定到您的每个方法调用:
constructor(db: Sources) {
this._updateDelayedRequestsCount = this._updateDelayedRequestsCount.bind(this);
db.source.on('update',this._updateDelayedRequestsCount);
this._updateDelayedRequestsCount();
}
也许它会解决您的问题。