MobX嵌套Store组件无响应求助:点击方块无法触发尺寸变化
在MobX嵌套Store中点击方块无法触发属性更新的解决方法
嘿,我帮你找出问题啦!你遇到的方块点击没反应、尺寸不更新的核心原因是回调函数的this绑定丢失——当你直接把MobXStore.square.toggleSelection传给onPointerUp时,这个函数执行时的this不再指向SquareModel的实例,导致this.selected = !this.selected根本没修改到可观察的selected属性,MobX自然不会触发组件更新。
下面给你三种可行的解决办法:
方法1:用箭头函数包裹回调
在App组件传递onPointerUp时,用箭头函数包裹一下,确保toggleSelection执行时this指向正确的SquareModel实例:
const App = observer(() => { return ( <svg className="App"> <svg x={100} y={100}> <Square unit={MobXStore.square.selected ? 2 : 1} onPointerUp={() => MobXStore.square.toggleSelection()} /> </svg> </svg> ); });
方法2:在构造函数中手动绑定this
修改SquareModel类,在构造函数里把toggleSelection的this绑定到实例上:
import { observable, action, decorate } from "mobx"; class SquareModel { constructor() { // 手动绑定this到当前实例 this.toggleSelection = this.toggleSelection.bind(this); } selected = false; toggleSelection() { console.log("toggle selection"); this.selected = !this.selected; } } decorate(SquareModel, { selected: observable, toggleSelection: action }); export default SquareModel;
改完之后,你就可以像原来一样直接传递MobXStore.square.toggleSelection作为回调了。
方法3:用class fields箭头函数定义action
利用ES6的class fields语法,把toggleSelection直接定义成箭头函数,这样this会自动绑定到实例,写法更简洁:
import { observable, action, decorate } from "mobx"; class SquareModel { selected = false; // 箭头函数自动绑定this到实例 toggleSelection = () => { console.log("toggle selection"); this.selected = !this.selected; }; } decorate(SquareModel, { selected: observable, toggleSelection: action }); export default SquareModel;
验证效果
修复this绑定问题后,点击方块时toggleSelection会正确修改selected的可观察属性,MobX会立刻感知到变化,触发App组件重新渲染,传递新的unit值给Square组件——作为observer的Square就会自动更新尺寸啦!
内容的提问来源于stack exchange,提问作者Ryan King
相关产品推荐
相关产品推荐

