What steps can I take to resolve the "this is undefined" issue in VueJS?

Whenever I include the line

this.$store.commit('disconnect');
, it throws a "this is undefined" error. Any suggestions on how to resolve this issue?

store/index.js :

export const state = () => ({
  log: false,
  user: {token: null, id: null, username: null, email: null, created_at: null, pseudo: null}
})


export const mutations = {
  connect (state) {
    state.log = true
  },
  disconnect (state) {
    state.log = false,
    state.user.id = null,
    state.user.username = null,
    state.user.email = null,
    state.user.created_at = null,
    state.user.pseudo = null
  }
}

index.vue

<script>
import axios from "axios";

  methods: {
    async login() {
    var self = this;

    const auth_res = axios({
      method:'post',
      url:'http://127.0.0.1:8000/v2.0/auth',
      data:{
        username: this.username,
        password: this.password
      }
      }).then(function(res){
        this.$store.commit('disconnect');
        self.$router.push('/');
      }).catch(function (erreur) {
        console.log(erreur);
      });
    }
  }
}
</script>

Everything works fine if I remove the commit line from the index.vue file. However, I need to use it for my functionality. Is there a way to fix this problem?

Thank you in advance.

Answer №1

When working with callbacks, it's important to remember that this refers to the callback function itself. This is likely the cause of your error message. To fix this, you can replace it with:

self.$store.commit('disconnect');

In this case, self holds the actual context of Vue. Here's a breakdown:

methods: {
    async login() {
    var self = this; // This captures the Vue method context

    const auth_res = axios({
      method:'post',
      ...
      }).then(function(res){
        self.$store.commit('disconnect'); // Now you have access to self.$store in the callback
        self.$router.push('/');
      }).catch(function (error) {
        ...
      });
    }
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with dynamically updating fields based on user input in real time

I have a goal to update a field based on the inputs of two other fields. Currently, all the fields are manual input. Below is the code I'm using to try and make the "passThru" field update in real-time as data is entered into the other fields. The ma ...

Find the most accurate color name corresponding to a hexadecimal color code

When given a hex-value, I aim to find the closest matching color name. For instance, if the hex-color is #f00, the corresponding color name is red. '#ff0000' => 'red' '#000000' => 'black' '#ffff00' = ...

Use the evernote findNotesMetadata function to efficiently retrieve all notes by implementing an offset and maxnotes parameter for looping through

According to the documentation provided by Evernote regarding findNotesMetadata, the maximum number of notes returned from the server in one response is 250. I am currently exploring how to handle multiple requests in order to retrieve the entire array if ...

ReactJS - Element not specified

I'm experiencing a specific issue with the component below related to the changeColor() function, which is triggering an error message: TypeError: Cannot set property 'color' of undefined This error seems to be isolated within this compo ...

Match rooms using Socket.io

I am utilizing the opentok and socket.io packages in an attempt to establish 2 distinct "groups". Successfully, I have managed to pair up individual users in a 1-to-1 relationship. However, my goal is to create two separate groups of users. For instance, ...

The function of the Angular ng-include form action for posting a URL appears to be malfunctioning

When a form post is included in a parent HTML using ng-include, it does not trigger the submission action. <div ng-include src="'form.html'"></div> The code in the form.html file is as follows: <form action="next/login" method = ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

Using AngularJS to toggle between two select dropdowns

I have two drop-down lists containing JSON data. <select class="form control" ng-model="fruitsName" ng-options="r.id as r.name for r in fruits"> <option value="">--Select---</option></select> $scope.fruits = [{'id': &apo ...

The function signature '(_event: React.SyntheticEvent, value: number) => void' cannot be assigned to the type 'FormEventHandler<HTMLUListElement>'

I am facing an issue with my component "PageFooter" being duplicated in three other components. I am trying to refactor it as a UI component. " I am getting the error message: 'Type '(_event: React.SyntheticEvent, value: number) = ...

When the limit is set to 1, the processing time is 1ms. If the limit is greater than 1, the processing time jumps to

Here is the MongoDB Native Driver query being used: mo.post.find({_us:_us, utc:{$lte:utc}},{ fields:{geo:0, bin:0, flg:0, mod:0, edt:0}, hint:{_us:1, utc:-1}, sort:{utc:-1}, limit:X, explain:true }).toArray(function(err, result){ ...

What is the correct way to register an imported component in a Vue single file component to comply with the eslint-plugin-vue vue/no-unregistered-components guideline?

Recently entering the realm of Vue, I'm in the process of achieving pristine eslint-plugin-vue outcomes on a trial project. However, when inspecting the test file named Home.vue displayed below, an alert is triggered: The "HelloWorld" compon ...

Using strings "true/false/null" in React Map render instead of true/false/null values

Imagine working in React, where I am looping through JSON data stored in the state variable this.state.searchData. Some of the data values returned from the API call may include true, false, or null. Here is an example: "active": true, "partition": n ...

Setting up computed properties in VueJSSetting up computed values in

I am currently working on developing a lottery number service, and I am curious about how to set up computed properties. I came across the Vue.js documentation for computed properties at https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties. I tr ...

Discover how to apply unique styles to specific HTML elements using their index values in jQuery

In the process of creating a party game similar to Tambola or Housie, I am faced with the challenge of automatically detecting and highlighting the numbers called out on each ticket in the game. For instance, if number 86 is announced, I aim to visually di ...

Expand the boundaries of the MUI Select to encompass a different element

Is there a way to extend the border of the MUI Select dropdown menu around the IconButton next to it? I have set up sorting options (A-Z, newest-oldest) using the Select component and included a button to reverse the direction (Z-A, oldest-newest). However ...

What is the best way to mandate multiple input fields in AngularJS?

I am currently working on creating a basic web page with a few input fields that must be filled out to proceed. Below is the code I have so far: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/l ...

Unexpected CORS error when fetching data with Ajax GET method

I have a question regarding CORS that I hope someone can help me with. I am currently working on an assignment for freecodecamp.com where I need to create a Wikipedia article search based on user input. However, I am struggling to understand how adding hea ...

Access the child scope's attribute within the parent scope in AngularJS

angular.module('myApp',[]) .controller('Parent',['$scope',function($scope){ //no specific definition }]).controller('Child',['$scope',function($scope){ $scope.user={name:''}; //create a us ...

Arranging by upcoming birthday dates

Creating a birthday reminder app has been my latest project, where I store names and birthdays in JSON format. My goal is to display the names sorted based on whose birthday is approaching next. Initially, I considered calculating the time until each pers ...

"Enhance Your Coding Experience with Visual Studio Code - TypeScript Definitions Catered

I am currently working on developing a basic web application using Node.js and Express. I have successfully installed both definitions using tsd following the steps outlined in this guide. When I run tsd query mongodb --action install, I do not encounter ...