Axios promise 中未定义的函数

Function Undefined in Axios promise

我在 asp.net mvc 应用程序中使用 ReactJs 和 Axios 时遇到以下问题

var ForgotPasswordForm = React.createClass({
baseUrl:  "http://localhost:28804/",

getInitialState : function(){
    return{isDisabled:false, text: 'Email Password Reset Link', errorText:''}
},

changeText : function(newText){
    this.setState({text:newText})
},

resetText : function(){
    this.setState({text: "Reset Password"})
},

setErrorText : function(error)
{
    this.setState({errorText:error})
},

enableButton: function(){
    this.setState({isDisabled:true});
},

disableButton: function(){
    this.setState({isDisabled:false});
},

handleSubmit: function(e){
    e.preventDefault();
    var email = this.refs.Email.getDOMNode().value.trim();
    if(!email)
    {  //TODO Show some sort of error message
        this.resetText();
        return;
    }
    var d = new FormData();
    d.append('Email', email);
    this.changeText('Please wait...');
    this.disableButton();
    console.log(d);
    var instance = axios.create({
        baseURL: this.baseUrl
    });
    instance.post('/Account/Login', d)
        .then(function(response){
            console.log(response);
            //I do not have a problem here
        }).catch(function(response){
           //this is where i always have an issue
         console.log(response);
         this.enableButton();
         this.resetText();
    });
    return;
},

render: function(){
    return (
        <form className="form-horizontal"   role="form" onSubmit={this.handleSubmit}>
           //Omitted for brevity
        </form>
    );
}
});
   ReactDOM.render(<ForgotPasswordForm/>, document.getElementById('form-fgt-pwd'));

问题是当请求失败时(故意的 500 内部服务器错误),我在浏览器控制台中得到以下输出

TypeError: this.enableButton is not a function

请问我做错了什么

提前致谢

.catch函数中this指的是全局范围(在浏览器中是window),其中没有方法enableButtonresetText、这些方法是 ForgotPasswordForm 对象的一部分,您需要为 catch 回调设置 this,您可以使用 .bind 方法

.catch(function(response){
   this.enableButton();
   this.resetText();
}.bind(this)); // set this for callback that refers to ForgotPasswordForm Object