You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在纯ES6类中访问MobX Store?React中可通过@inject轻松实现

嘿,这个问题我之前也纠结过!其实在纯ES6类里访问MobX Store完全不需要依赖React的@inject,有好几种简单直接的方式,我给你捋捋:

最直接的方式:直接导入Store实例

我们平时创建MobX Store的时候,通常会直接导出一个实例(而不是类本身),这样不管是React组件还是纯ES6类,都能直接导入使用:

第一步:创建并导出Store实例

// stores/MyStore.js
import { makeAutoObservable } from "mobx";

class MyStore {
  constructor() {
    makeAutoObservable(this);
  }

  myMethod() {
    console.log("执行Store里的方法");
  }
}

// 直接导出实例,而不是类
export default new MyStore();

第二步:在纯ES6类中导入并使用

// 你的纯ES6类文件
import myStore from './stores/MyStore';

class PlainES6Class {
  executeStoreMethod() {
    // 直接调用Store的方法
    myStore.myMethod();
  }
}

// 使用示例
const instance = new PlainES6Class();
instance.executeStoreMethod();

多Store场景:用Store管理器统一管理

如果你有多个Store,不想到处写零散的导入,可以创建一个Store管理器,把所有Store实例集中起来:

// stores/index.js
import MyStore from './MyStore';
import UserStore from './UserStore';

export const storeManager = {
  myStore: MyStore,
  userStore: UserStore
};

然后在纯类里这样用:

import { storeManager } from './stores';

class AnotherPlainClass {
  doSomething() {
    storeManager.myStore.myMethod();
    storeManager.userStore.fetchUserInfo();
  }
}

需要动态注入的场景:手动传递Store实例

如果你的纯类需要在不同环境使用不同的Store实例(比如测试环境用Mock Store),可以通过构造函数手动传递Store:

class FlexiblePlainClass {
  constructor(store) {
    this.myStore = store;
  }

  run() {
    this.myStore.myMethod();
  }
}

// 使用时传入Store实例
import myStore from './stores/MyStore';
const flexibleInstance = new FlexiblePlainClass(myStore);
flexibleInstance.run();

补充说明

React里用@inject是因为React组件依赖上下文机制,方便在组件树中传递Store,同时支持SSR等场景下的动态替换。但纯ES6类没有这些限制,直接导入实例或者手动注入是最轻便的方案,完全能满足需求~

内容的提问来源于stack exchange,提问作者Ignacio Segura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:07:32