Why do I keep receiving the error message "Cannot set property of undefined"?

In the midst of a small project that involves utilizing nuxt, js, and axios, I encountered an issue when attempting to assign the response data to my formFields object. Despite having declared formFields within the data section, I kept receiving an error message stating 'undefined' in the console. Here is a snippet of my code:

Code snippet:

editCustomers (customerId, submit = false) {
  this.editMode = true
  this.customerId = customerId
  if (submit === 1) {
    // this.$Progress.start()
    this.$axios.$post('mydomain.com' + customerId + '/1', $('#add-customer').serialize()).then(function (data) {
      this.validation(data)
      // another form validation again using the helper
      this.refresh = true
    })
    // this.$Progress.finish()
  } else {
    this.$axios.$get('mydomain.com' + customerId).then(function (data) {
      this.formFields = data.customers[0]
    })
  }
}

Variables in my data section:

data () {
return {
  laravelData: {},
  formFields: {},
  search: null,
  editMode: true,
  customerId: null,
  refresh: false
}
 }

Despite correctly declaring the data variables, the assignment

this.formFields = data.customers[0]
resulted in the following error message:

Uncaught (in promise) TypeError: Cannot set property 'formFields' of undefined

Answer №1

Modify this section:

this.$axios.$get('mydomain.com' + customerId).then(function (data) {
  this.formFields = data.customers[0]
})

Update it to the following:

this.$axios.$get('mydomain.com' + customerId).then((data) => {
  // Now you have access to your class instance
  this.formFields = data.customers[0]
})

Answer №2

When working with JavaScript, this typically refers to the current target within the current scope. With the function keyword used to declare a function, this points to the object that invoked the function.

If you notice that in your code, the reference of this doesn't point to the Vue instance anymore; instead, it defaults to undefined, likely due to the callback being executed without a specific context for this. One way to resolve this is by storing the reference of this outside the function and enclosing it in its closure:

editCustomers (customerId, submit = false) {
  this.editMode = true
  this.customerId = customerId
  const vm = this; // vm = this = Vue instance
  if (submit === 1) {
    // this.$Progress.start()

    this.$axios.$post('mydomain.com' + customerId + '/1', $('#add-customer').serialize()).then(function (data) {
      // vm = Vue instance; this = undefined
      vm.validation(data)
      // another form validation again using the helper
      vm.refresh = true
    })
    // this.$Progress.finish()
  } else {
    this.$axios.$get('mydomain.com' + customerId).then(function (data) {
      // vm = Vue instance; this = undefined
      vm.formFields = data.customers[0]
    })
  }
}

ETA: To further clarify the concept of this:

function myName() { return this.name};
var obj = {name:'test'};
var objName = myName.bind(obj); // a new function where the `this` arg is bound to `obj`
var text = objName(); // text === 'test'
console.log(text);

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

The error "Property 'user' does not exist on type 'Session'." occurred while attempting to pass session data using express-session and accessing req.session.user

I'm currently working on creating a basic login form for users to access a website, where I plan to store their session data in a session cookie. The express-session documentation provides the following example for setting it up: app.post('/login ...

Configuring universal sass variables within a vue application

After following the instructions in the documentation to create a vue.config.js file and set some global sass variables, I encountered an issue where the variables were undefined when accessed in a component. Manually adding the import statement in the com ...

Choosing the subsequent element that comes before

<tr class="main"></tr> <tr class="emails-details"> <button>some button</button> </tr> <tr class="main"></tr> <tr class="emails-details"> <button>some button</button> </tr> &l ...

Currently troubleshooting an issue with the CSS that is affecting the table header alignment

At first, I posed this Question and developed my own plugin to accomplish the task. However, I am encountering an unusual CSS issue with the table. Once I applied the plugin, the borders of table cells became disorganized. Here is a jsFiddle showcasing ...

Secure Flask API used for serving JSON files to a basic HTML, JavaScript, and CSS web application

I have developed a basic web application that will display data in a table and be updated on a weekly basis. To perform this update, I utilize Python code in the backend to scrape and modify data before storing it in a SQLite database. After some researc ...

I'm not entirely sure why I keep getting the error message stating "Cannot read property 'innerHTML' of null"

Having an issue with my JavaScript code where I am trying to insert a new table row into the HTML but keep getting an error message that says "Uncaught TypeError: Cannot read property 'innerHTML' of null" <!DOCTYPE html> <html lang=" ...

Simultaneous Loading: Marvelous Vue Preloader Spinner and Content Display (Vuejs)

Is there a way to ensure that the preloader loads before displaying the content? I tried using the library from , but both the preloader and content load simultaneously. How can I make sure that the preloader loads first, followed by the content? Thank you ...

Maximizing Content Width in FullCalendar v5 to Ensure Screen Compatibility

As I develop a calendar and timeline view using fullcalendar v5, my clients are requesting a month view that displays the entire month without any scroll bars. While I am aware of setting the contentHeight to auto, there seems to be no option for adjusting ...

Struggling to transmit data to material dialog in Angular2+

I am facing an issue with my Material Dialog not working properly. Can anyone point out what I might be missing? product-thumbnail.ts I will use this to trigger the dialog export class ProductThumbnailComponent implements OnInit { @Input() product: Pr ...

Enhance the efficiency of DataTable by optimizing cell class modifications

I have been very pleased with the performance of jquery DataTables, but I have encountered a situation where I need to optimize it further. Specifically, I am updating the class of a cell based on its data. Currently, I am achieving this by using the ren ...

Sending dynamic data from PHP to jQuery flot pie chart

In my PHP code, I have defined 3 variables. $record = "283-161-151"; $rec = explode("-", $record); $win = $rec[0]; $draw = $rec[1]; $loss = $rec[2]; The variables $win, $draw, and $loss are displaying correctly, indicating they are working as intended. ...

Exploring AngularJS: The Innovative Navigation Bar

My goal is to incorporate the functionality demonstrated in this example: https://material.angularjs.org/1.1.1/demo/navBar To achieve this, I have created the following index.html: <!DOCTYPE html> <html lang="en"> <head> &l ...

How can you use jQuery to select and manipulate a wildcard href ID?

There are multiple links listed below: <a href="http://www.google.com" id="link01">Google</a> <a href="http://www.yahoo.com" id="link02">Yahoo</a> <a href="http://www.cnn.com" id="link03">CNN</a> <a href="http://www. ...

Utilizing Radio buttons for validation in react-hook-form

After creating a form with radio buttons and implementing validation using React Hook Form, I encountered an issue where the console always displayed "on" regardless of the selected radio button. <div className=""> <label ...

Is it possible for my OAuth2 callback page to share the same HTML page? Also, what is the process for obtaining the token?

In my setup, I am working with static html and javascript along with C# Web API. One of the scenarios I encountered involves a link that triggers an oauth2 server from my HTML file named index.html. The question arises: Is it appropriate to establish the c ...

HTML- Any suggestions on how to troubleshoot my sticky navbar not functioning properly?

I'm having trouble creating a sticky navbar. I've attempted to use z-index: 999 but it's not behaving as expected. * { margin: 0; padding: 0; } .navbar { display: flex; align-items: center; justify-items: center; position: ...

How can you convert Promise.all to a single Promise?

I have successfully implemented two API calls using Promise.all method with no issues. Even though one API call is sufficient to retrieve the results, I decided to stick with Promise.all and it's still working fine. I attempted to replace Promise.al ...

Issue in VueJs where mutations do not properly save new objects to the state

I am facing an issue with updating my vuex store after modifying my user credentials in a component. Below is the code snippet for reference: mutations: { updateUserState: function(state, user) { state.user = user; }, } actions: { updat ...

Struggling to get my Vue.js unit test to pass with test-utils

I'm currently testing a specific part of my Heading.vue component <v-layout column align-center justify-center> <img src="@/assets/images/logo.png" alt="Logo-Choro-des-Charentes" height="200"> <h1 class="mb-2 disp ...

Using Jquery to toggle the visibility of a DIV element and adding a blinking effect when it becomes visible

I have a hidden div that is displayed when a link is clicked, and I want it to blink as well. Here is my current setup: The link to display the hidden div: <a class="buttons" href="#" onclick="show(this)">join us</a> The hidden div to be di ...