背景
最近尝试在taro里用Mobx管理全局状态,发现有些在mobx的store中定义的函数可以访问到this,有些不能,在此贴一下主要代码的复现及解决方案
代码复现
// personInfoStore.ts
import {observable} from 'mobx';
const personInfoStore = observable({
_sex: '1',
counterStore(){
},
setSex(sex:string):void{
this._sex=sex;
},
get sex(){
return this._sex;
}
})
export default personInfoStore;
// a.jsx
<FirstStep
sex={personInfoStore.sex}
setSex={ (item)=>personInfoStore.setSex(item)} // 在personInfo.tsx的setSex里访问this就能正常访问了
// setSex={ personInfoStore.setSex} 这样写的话,在personInfo.tsx中的setSex里访问this就是undifined
/>
// FirstStep.tsx
const FirstStep = () => {
return (
<RadioGroup
value={ sex }
onChange={ (item)=>setSex(item.detail) }
direction="horizontal"
> </RadioGroup>
)
}