Mobx 强制更新计算值

Mobx forcing computed values to update

我正在使用 Mobx 来处理我的 React 应用程序中的一些状态。

我的应用程序使用 JWT 进行身份验证。通过令牌和刷新令牌。

我已经建立了一家商店,其运作方式如下:

class generalStore {
    isLoggedIn = localStorage.getItem('token') !== null ? true : false;
    name = localStorage.getItem('token') !== null ? jwtdecode(localStorage.getItem('token')).name : null;
    role = localStorage.getItem('token') !== null ? jwtdecode(localStorage.getItem('token')).role : null;

    login(name, role) {
        this.isLoggedIn = true;
        this.name = name;
        this.role = role;
    }

    logout() {
        this.isLoggedIn = false;
        this.name = null;
        this.role = null;
    }
}

decorate(generalStore, {
    isLoggedIn: observable,
    name: observable,
    role: observable,
    login: action,
    logout: action
})

const store = new generalStore()

当在应用程序的其他地方调用 login/logout 时,这会按预期工作。

但是,如果 JWT 格式错误(通过开发控制台手动),jwtdecode 函数会抛出错误并且整个应用程序会崩溃——这并不理想。我可能有点偏执,畸形的 JWT 不应该在野外经常发生,但我喜欢健壮。

然后我想我可以使用计算值来缓解这个问题:

class generalStore {
    constructor() {
        try {
            this.decoded = jwtdecode(localStorage.getItem('token'))
        } catch(err) {
            this.decoded = null
        }
    }

    get isLoggedIn() {
        if (this.decoded) {
            return true
        } else {
            return false
        }
    }


    get name() {
        if (this.decoded) {
            return this.decoded.name
        } else {
            return false
        }
    }

    get role() {
        if (this.decoded) {
            return this.decoded.role
        } else {
            return false
        }
    }
}

decorate(generalStore, {
    isLoggedIn: computed,
    name: computed,
    role: computed,
})

但是当本地存储在登录时使用新令牌更新时,计算值不会自动更新,在计算值反映现在存在的令牌之前,必须刷新应用程序(因此也刷新商店)。

有没有办法强制更新计算值?或者我可以处理 jwtdecode 在我的商店中定义可观察对象时抛出的错误吗(第一个代码块)?

或者我不应该担心格式错误的 JWT?如果我负责的话,我似乎应该...

我认为这是行不通的,因为 this.decoded 不可观察,因此 mobx 无法跟踪更新以强制更新计算的 属性。

在所有 mobx examples 中,他们使用基于其他可观察值的计算属性。

因此您的选择是使 decoded 可观察,或者使用方法而不是计算 属性。

class generalStore {

    decoded = null;

    constructor() {
        try {
            this.decoded = jwtdecode(localStorage.getItem('token'))
        } catch(err) {
            this.decoded = null
        }
    }

    // ...
}

decorate(generalStore, {
    decoded: observable,
    // ...
});