Javascript React Native setState不是函数

Javascript React Native setState不是函数,javascript,reactjs,function,react-native,setstate,Javascript,Reactjs,Function,React Native,Setstate,有人能解释一下为什么这个.setState不是一个函数吗 我不明白为什么我的代码有错误 import React from 'react'; import axios from 'axios' import { StyleSheet, Text, View , Image} from 'react-native'; export default class App extends React.Component { constructor(){ super();

有人能解释一下为什么这个.setState不是一个函数吗

我不明白为什么我的代码有错误

import React from 'react';
import axios from 'axios'
import { StyleSheet, Text, View , Image} from 'react-native';

export default class App extends React.Component {

    constructor(){
        super();
        this.state = {res: []}
    }
    componentDidMount() {
        axios.get('https://api.github.com/repos/torvalds/linux/commits')
            .then(function (response) {
                this.setState({res: response});
            }).catch(function (error) {
                console.log(error);
            });
    }
 }
谢谢

这是一个问题。使用


出现错误的原因是
未引用axios解析器功能中的组件类上下文。您可以将解析器函数用作胖箭头函数,以使代码正常工作,如下所示:

componentDidMount() {
    axios.get('https://api.github.com/repos/torvalds/linux/commits')
        .then((response) => {
            this.setState({res: response});
        }).catch(function(error) {
            console.log(error);
        });
}
componentDidMount() {
     let self = this;
     axios.get('https://api.github.com/repos/torvalds/linux/commits')
         .then(function(response) {
             self.setState({res: response});
         }).catch(function(error) {
             console.log(error);
         });
 }
或者您可以将其更改为以下内容:

componentDidMount() {
    axios.get('https://api.github.com/repos/torvalds/linux/commits')
        .then((response) => {
            this.setState({res: response});
        }).catch(function(error) {
            console.log(error);
        });
}
componentDidMount() {
     let self = this;
     axios.get('https://api.github.com/repos/torvalds/linux/commits')
         .then(function(response) {
             self.setState({res: response});
         }).catch(function(error) {
             console.log(error);
         });
 }

使用arrow函数包装
this.setState({res:response})
带到内部箭头功能