如何在React+Mobx中不使用装饰器使用Inject?
inject Without Decorators Let's break down what's going wrong here and get your MobX setup working correctly, including covering the decorator-free inject usage you asked about.
First: Why the "onPut is not defined" Error?
In your Image component's render method, you're trying to reference onPut directly like it's a local variable—but inject doesn't inject variables into the component's scope. Instead, it adds the injected values to the component's props.
You need to access it via this.props.onPut. Here's the fixed Image component code:
//components/Image import React, { Component } from 'react'; import { observer, inject } from 'mobx-react'; class Image extends Component { render() { // Destructure onPut from the component's props const { onPut } = this.props; return ( <div> {onPut} </div> ); } } // This is already the decorator-free way to use inject! export default inject(({ imSt }) => ({ onPut: imSt.list.keyword, }))(observer(Image));
Second: Using inject Without Decorators (As You Wanted)
Great news—your current inject usage is already the decorator-free approach! Decorators would look like this:
// Decorator-based syntax (requires Babel setup for decorators) @inject(({ imSt }) => ({ onPut: imSt.list.keyword })) @observer class Image extends Component { render() { const { onPut } = this.props; return <div>{onPut}</div>; } } export default Image;
By wrapping your component with inject(...)(), you're avoiding decorators entirely—this is the standard function-composition way to apply MobX's HOCs (Higher-Order Components) without decorator syntax.
Quick Check of Your Other Code
Your imageStore and Home component code look correct:
- You're using
decorateto marklistas observable (another decorator-free win!) - You're instantiating the store and passing it to
Providerproperly
Once you fix the props access in the Image component, the "onPut is not defined" error should disappear, and you'll see the yoyo keyword rendered on the page.
内容的提问来源于stack exchange,提问作者James Thomas

