0

I'm making a simple axios call and on success, call a toast. The toast function is also there and working fine because I am using it at 100 different places.

console log shows {data: "Payment Successful", status: 200, statusText: "OK", headers: {…}, config: {…}, …} means the call is working fine, it's just the this is not ...

this.razorPayOptions = {
    'key': process.env.MIX_RAZORPAY_KEY,
    'name': process.env.MIX_APP_NAME,
    'description': 'Details ...',
    'handler': function (request) {
        axios.post('/api/transaction/complete', request)
            .then(response => {
                console.log(response);
                this.toast(response.data, response.status); // this is where the error occurs
            });
    }
}

Error: Uncaught (in promise) TypeError: _this.toast is not a function

I've searched on internet for past 2 days but couldn't find anything. Some suggested to use async/await but no luck either. As always, stack overflow is my last resort. If you need more info, please add a comment below.

Thank You.

Digvijay
  • 7,836
  • 3
  • 32
  • 53

3 Answers3

3

Switch your handler to an arrow function to avoid changing the scope:

this.razorPayOptions = {
    'key': process.env.MIX_RAZORPAY_KEY,
    'name': process.env.MIX_APP_NAME,
    'description': 'Details ...',
    'handler': (request) => {
        axios.post('/api/transaction/complete', request)
            .then(response => {
                console.log(response);
                this.toast(response.data, response.status); // this is where the error occurs
            });
    }
}

Check out this answer for more context

cuzox
  • 794
  • 7
  • 15
2

You can either switch to an arrow function, or capture this before you define your callback:

this.razorPayOptions = {
    'key': process.env.MIX_RAZORPAY_KEY,
    'name': process.env.MIX_APP_NAME,
    'description': 'Details ...',
    'handler': function (request) {
        const that = this;
        axios.post('/api/transaction/complete', request)
            .then(response => {
                console.log(response);
                that.toast(response.data, response.status); // this is where the error occurs
            });
    }
}
Will Jenkins
  • 9,507
  • 1
  • 27
  • 46
0

The problem is that you are misreading the scope. To solve your problem, change the function for an arrow function.

this.razorPayOptions = {
'key': process.env.MIX_RAZORPAY_KEY,
'name': process.env.MIX_APP_NAME,
'description': 'Details ...',
'handler': (request) => {
    axios.post('/api/transaction/complete', request)
        .then(response => {
            console.log(response);
            this.toast(response.data, response.status); // this is where the error occurs
        });
   }
}

could you read this post https://www.codementor.io/@dariogarciamoya/understanding-this-in-javascript-with-arrow-functions-gcpjwfyuc.