我认为这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
没有被调用,就像 if 中发生错误clearRequestsFromIndexedDb
,但没有错误。所以我回滚到箭头功能,一切都恢复正常了。它会影响什么吗?或者问题实际上在我失踪的其他地方?