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

如何连接 Mobx6 商店以响应 15.8 组件? '未捕获的不变违规,只能在函数组件体内调用 Hooks''

如何解决如何连接 Mobx6 商店以响应 15.8 组件? '未捕获的不变违规,只能在函数组件体内调用 Hooks''

我正在尝试将 mobx 商店连接到我的 React 组件。

库版本:

 "mobx": "^6.3.2"
 "mobx-react": "^7.2.0"
 "react": "16.8.2"
 "react-dom": "16.8.2"

以下是最小的示例代码

A.tsx

const root_store = new RootStore();

ReactDOM.render(
    <Provider root_store={root_store}>
        <IApp></IApp>
    </Provider>,document.getElementById('root'),);

B.tsx(用于 IApp 组件 ^^)

interface Props {
    root_store?: RootStore;
}

class App extends React.Component<Props> {
    render(): any {    
        return (
            <div>
                 <IEventsEmbedSkin />
            </div>
        )
    }
}


export const IApp = inject(({root_store}:{root_store:RootStore}) => {
    console.log(root_store);
    return {
        root_store: root_store,};
})(observer(App))

C.tsx(用于 IEventsEmbedSkin 组件 ^^ )

interface Props {
    root_store?: RootStore;
}

class EventsEmbedSkin extends React.Component<Props> {
    
    render(): JSX.Element {
        return (
            <div></div>
        );
    }
}

export const IEventsEmbedSkin = inject(({root_store}:{root_store:RootStore}) => {
    console.log(root_store);
    return {
        root_store: root_store,};
})(observer(EventsEmbedSkin));

如果我不渲染文件 B.tsx 中的 IEventsEmbedSkin 组件(从文件 C.tsx 导入),则在文件 B 中一切正常,react 响应任何商店更新。当我渲染 IEventsEmbedSkin 组件(从文件 C.tsx 导入)时,出现此错误

未捕获的不变违规:只能在函数组件的主体内部调用钩子。

组件出现上述错误

未捕获的不变违规:只能在函数组件的主体内部调用钩子。

任何人都可以帮助我解决正在发生的事情吗?

我无法更改我的 React 版本。

我的商店看起来像这样:

rootstore.tsx

export class RootStore {
    context_store: ContextStore;
    recording_store: RecordingStore;

    constructor(props: Props) {

        this.context_store = new ContextStore({
            root_store: this,}); 

        this.recording_store = new RecordingStore({
            root_store: this,});
    }
}

contextstore.tsx

export class ContextStore {
    root_store: RootStore;
    status: 'pending' | 'error' | 'done' | 'debug' = 'debug';

    constructor(props: Props) {
        this.root_store = props.root_store;    

        makeObservable(
            this,{
                status: observable,initialise: action,},{
                autoBind: true,);
    }

    public async initialise(): Promise<void> {
        this.status = 'pending';
        try {
            const data = await this.api_store.get_config_and_instance_data();

            runInAction(() => {
                this.status = 'done';
            });
        } catch (e) {
            runInAction(() => {
                this.status = 'error';
            });
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。