为什么我的代码使用箭头函数而使用绑定



我曾认为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();
}

也许它能解决你的问题。

最新更新