3

我在 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

请问我做错了什么

提前致谢

4

1 回答 1

2

in .catchfunctionthis是指全局作用域(在浏览器中是window),没有methods的地方enableButtonresetText这些methods是ForgotPasswordFormobject的一部分,需要设置thiscallback catch,可以用.bindmethod

.catch(function(response){
   this.enableButton();
   this.resetText();
}.bind(this)); // set this for callback that refers to ForgotPasswordForm Object
于 2015-12-15T14:34:31.973 回答