使用mobx的decorate时出现Object(...) is not a function错误求助
解决Mobx中使用decorate方法触发TypeError的问题
你遇到的这个Uncaught TypeError: Object(...) is not a function错误,我帮你梳理下问题根源和修复方案:
首先看你的错误栈,问题出在decorate方法的调用处,结合你的代码来看,主要有几个关键问题需要修正:
问题1:类中未初始化要装饰的属性
你把@observable vrp_solution = {};注释掉了,但没有在类的其他地方(比如constructor)初始化这个属性。Mobx的decorate方法需要类上确实存在这个属性才能完成装饰,否则就会触发异常。
问题2:访问类属性时遗漏了this
在handleClick方法里,你直接写vrp_solution= "!";,这会创建一个全局变量,而不是访问类的可观察属性,这不仅达不到预期效果,也可能间接导致装饰逻辑出错。
问题3:类名不符合React规范(非致命但建议修复)
React组件类名要求首字母大写,componentName改成ComponentName可以避免一些潜在的识别问题。
修复后的完整代码
import React, { Component } from 'react' import { Button } from 'semantic-ui-react' import axios from 'axios' import { decorate, observable } from "mobx" // 修正类名首字母大写 class ComponentName extends Component { constructor () { super() this.state = { solution: [] } // 初始化要装饰的属性 this.vrp_solution = {}; this.handleClick = this.handleClick.bind(this) } handleClick () { axios.post('http://localhost:8000/vrp/') .then(response => { // 加上this访问类的可观察属性 this.vrp_solution = "!"; console.log(response) }) } render() { return ( <Button onClick={this.handleClick}> Calculate Best Routes! </Button> ) } } // 正确使用decorate装饰属性 export default decorate(ComponentName, { vrp_solution: observable });
额外方案:使用装饰器语法(可选)
如果你更习惯用@observable装饰器,可以不用decorate方法,但需要确保你的项目配置支持装饰器(比如在Babel中配置@babel/plugin-proposal-decorators),代码会更简洁:
import React, { Component } from 'react' import { Button } from 'semantic-ui-react' import axios from 'axios' import { observable } from "mobx" class ComponentName extends Component { @observable vrp_solution = {}; constructor () { super() this.state = { solution: [] } this.handleClick = this.handleClick.bind(this) } handleClick () { axios.post('http://localhost:8000/vrp/') .then(response => { this.vrp_solution = "!"; console.log(response) }) } render() { return ( <Button onClick={this.handleClick}> Calculate Best Routes! </Button> ) } } export default ComponentName;
内容的提问来源于stack exchange,提问作者simo
相关产品推荐
相关产品推荐

