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

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

如何解决调用回调函数时,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 举报,一经查实,本站将立刻删除。