微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我的代码可以使用箭头函数而被绑定破坏?

如何解决为什么我的代码可以使用箭头函数而被绑定破坏?

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

也许它会解决您的问题。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。