Uncaught TypeError: this.setState is not a function at XMLHttpRequest.httpRequest.onreadystatechange

This dev tip is brought to you by the developer of MoneyPhone: Personal Expense Tracking for Android and iOS. Consistently spend less than you earn each month and get your finances under control when you start monitoring your expenses with MoneyPhone!

this.setState not a function at XMLHttpRequest? Here’s the quick fix you are looking for friend…

var that = this; that.setState({/* json goes here */});

Essentially, that’s all there is to it. The problem is when onreadystatechange fires asynchronously, this will no longer reference the same “this”. So, we simply create another variable called “that” which references the “this” we want. I know all of this gobbledygook about “this” and “that” and whatnot problably is not making any sense. So here is a little example code for reference:

handleRefreshData(paramOne, paramTwo, oldState) {
var that = this;
var httpRequest = new XMLHttpRequest();
var httpRequestURL = "https://mysupersweetdomain.com/my-route";
httpRequest.open("POST", httpRequestURL, true);
httpRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Get Response Data
var data = this.responseText;
data = JSON.parse(data);
// Update State With Fresh Financial Data HERE
var newState = oldState;
newState.foo = data.foo;
newState.bar = data.bar;
newState.baz = data.baz;
that.setState(newState); // update state with fresh financial data
var formData = new FormData();
formData.append("abc", paramOne);
formData.append("xyz", paramTwo);
view raw thatEqualsThis.js hosted with ❤ by GitHub