Javascript 无法设置属性';x';未定义的

Javascript 无法设置属性';x';未定义的,javascript,reactjs,mobx,mobx-react,Javascript,Reactjs,Mobx,Mobx React,我想在存储区设置变量。 这是我的商店 class storeCategory{ @observable categories =[]; @action getCategories = () =>{ fetch('http://localhost:3000/categories') .then((resp) => resp.json()) .then(function(resp2){ this.

我想在存储区设置变量。 这是我的商店

class storeCategory{

    @observable categories =[];

    @action getCategories = () =>{
        fetch('http://localhost:3000/categories')
        .then((resp) => resp.json())
        .then(function(resp2){
            this.categories=resp2;
        });
    }


}
这是我的组件

@inject('sCategory')
@observer
class Category extends React.Component{

    componentDidMount=()=>{
       this.props.sCategory.getCategories();
    }

    render(){
        const {sCategory} = this.props;
        return (
            <ListGroup>
                {this.props.sCategory.categories.map((cat, index) => {
                            return (
                                <ListGroupItem key={cat.id}>{cat.categoryName}</ListGroupItem>
                            )
                        })}
            </ListGroup>
          );
    }
}
@inject('sCategory'))
@观察者
类类别扩展了React.Component{
componentDidMount=()=>{
this.props.sCategory.getCategories();
}
render(){
const{sCategory}=this.props;
返回(
{this.props.sCategory.categories.map((cat,index)=>{
返回(
{cat.categoryName}
)
})}
);
}
}
我添加到sCategory到index.js的提供者

我在fetch方法中的this.categories=resp2中得到这个错误

无法设置未定义的属性“类别”


改用箭头功能:

@action getCategories = () =>{
    fetch('http://localhost:3000/categories')
    .then((resp) => resp.json())
    .then((resp2) => {
        this.categories=resp2;
    });
}`

function关键字将“this”关键字绑定到自身,但arrow函数将其绑定到上下文

如果调用的属性是一个函数,例如()缺失或太多,也会得到该属性。昨天我发疯了,因为一个变量来自类型NUMBER,而不是一个等待的字符串(我只添加了+”,一切都很好…)。所以我使用的字符串函数没有为这个变量值定义,因为它被表示为number。如果你试图对这样一个由“残缺函数”处理的值执行操作,它将变成“未定义”。如果函数不返回任何内容,也会发生同样的情况。因此,请检查它失败的地方发生了什么。:)