Acabo de jugar con un código con mobX, y esto sucedió, no sé por qué, pero estoy seguro de que no es muy diferente de los documentos oficiales.
Aquí está store.tsx
import { observable, computed, action, makeObservable, override, makeAutoObservable } from "mobx" class CounterStore { initValue = 0 powValue = Math.pow(this.initValue, 2) constructor() { makeAutoObservable(this) } increaseNumber() { this.initValue = this.initValue + 1 } } const Store = new CounterStore() export default StoreAquí es donde uso esto. llamado aumento.tsx
import { observer } from "mobx-react" export const IncrementButton = observer(({ store }) => { return ( <div> <button onClick={store.increaseNumber}>Increase</button> <h1>{store.initValue}</h1> </div> ) })Y index.tsx
ReactDOM.render( <React.StrictMode> <IncrementButton store={Store} /> {/* <TestUseState /> */} {/* <TestEffect /> <UseMemoTest /> */} </React.StrictMode>, document.getElementById("root"), Extraño es, muestra initValue , pero cuando hago clic en aumentar, muestra can't not read properties Por favor, ayuda, gracias.
como notó @mimoid, su método no está vinculado a la clase y pierde contexto ( this ). No es un problema de MobX, es solo una característica regular de javascript llamada enlace tardío .
Aunque realmente no necesita cambiar makeAutoObservable a makeObservable , solo puede usar funciones de flecha, en mi opinión, es una forma más "nativa":
class CounterStore { initValue = 0 powValue = Math.pow(this.initValue, 2) constructor() { makeAutoObservable(this) } // Just make it an arrow function increaseNumber = () => { this.initValue = this.initValue + 1 } }Cambie makeAutoObservable a makeObservable y asigne manualmente action.bound a cada acción en lugar de action . Tuve un error similar y lo resolvió.