调用回调函数时,mobx react lite 迁移“this”未定义

问题描述

我已经迁移到 react mobx lite,但虽然我有一个解决方案,但我不明白下面的错误

当通过 rootStore.view.openWithCallback 调用回调方法时,我得到“这是未定义的”。要修复它,我必须绑定商店,但不确定这是否应该像那样修复。 (在 mobx-react - 不是 lite - 这工作正常)

// index.js
const rootStore = new RootStore(locale)
const StoreContext = React.createContext(rootStore);
export const useStores = () => React.useContext(StoreContext);
export const StoreProvider = ({children,rootStore}) => {
  return (
      <StoreContext.Provider value={rootStore}>{children}</StoreContext.Provider>
  );
};


ReactDOM.render(
      <StoreProvider rootStore={rootStore}>
      <App />
      </StoreProvider>,document.getElementById('root')
);


const routes = [
  { path: '/',action: () => rootStore.view.openWithCallback("/",rootStore.view.noop,true,true) },{ path: '/account',action: () => rootStore.view.openWithCallback("/account",rootStore.user.getAddresses) },...]
const router = new UniversalRouter(routes)
router.resolve(window.location.pathname)

rootStore.user.getAddresses 是回调。如果我将其更改为 rootStore.user.getAddresses.bind(rootStore.user) 它可以工作,但是有没有更优雅的方法来实现相同的目标?

下面有更多代码来帮助理解我可能做错了什么。谢谢!

// from ViewStore (RootStore->ViewStore)
@action.bound
    async openWithCallback(page,callback,initCat = true,awaitRequested = false) {

        this.loading = true
        this.page = page
        if (awaitRequested) {
            await this.init(initCat)
        } else {
            this.init(initCat)
        }

        await callback() // CALLBACK FOR rootStore.user.getAddresses
       
        runInAction(() => {
            this.loading = false
        })
        this.ga(this.page) //Google Analytics
    }

// from RootStore
export default class RootStore {
    view
    user,...
   
    constructor(browserLocale) {
        makeAutoObservable(this)
        this.user = new UserStore(this)
        this.view = new ViewStore(this)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)