0

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

4

1 回答 1

-1

我看到你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();
    }

也许它会解决你的问题。

于 2021-06-07T07:42:45.770 回答