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

PWA JavaScript struggling with GPS geolocation coordinates

I am experiencing issues with the GPS coordinates being stuck when using geolocation in a Progressive Web App (PWA). Sometimes, the coordinates get stuck at the previous location, even if the user has moved since then. I suspect that this is due to the GP ...

What steps can you take to convert your current menu into a responsive design?

I am currently developing a website using PHP, HTML, and CSS. The site is not responsive, and I want to make the menu responsive. My global navigation and admin interface are not adapting properly as they are designed using tables. Is there a method I can ...

classes_1.Individual is not a callable

I am facing some difficulties with imports and exports in my self-made TypeScript project. Within the "classes" folder, I have individual files for each class that export them. To simplify usage in code, I created an "index.ts" file that imports all class ...

The component name 'Hidden' is not valid for use in JSX

Currently, I'm immersed in a personal project focused on creating a responsive website utilizing Material-UI. In this endeavor, I've leveraged React and kickstarted the project with create-react-app. To enhance the design, I incorporated code fro ...

Creating a delayed queue using RxJS Observables can provide a powerful and

Imagine we have a line of true or false statements (we're not using a complicated data structure because we only want to store the order). Statements can be added to the line at any time and pace. An observer will remove items from this line and make ...

ElementUI Cascader not rendering properly

Utilizing elementUI's cascading selector to present data, I have crafted this code in accordance with the official documentation. <el-cascader v-model="address" :options="addressOptions" :props="{expandTrigger: 'hover'}" ...

Exposing a Hidden Division with a Link via jQuery

I currently have a jQuery Panel set up to open when clicking a button. Now, I am looking to add a second link at the bottom of the page that will also open the same panel. Can anyone provide guidance on how to accomplish this? You can view my JSFiddle a ...

stream a song with a font awesome symbol

Can an audio track be played using a font awesome icon, such as displaying the song name (mp3) with a play icon right next to it? When users click on the play icon, can the track start playing and be paused or stopped at will? The list will consist of app ...

Is it possible to create an instance of a superclass and automatically instantiate a specific subclass based on the parameters provided?

Currently, I am utilizing Google's GSON package which can be found at this link My task involves converting JSON data to Java objects. Below is a snippet of the code where the conversion process takes place: Gson gson = new Gson(); Type collectionT ...

Tips for optimizing the processing speed of large XML files using jQuery, Javascript, and PHP

Currently, I am developing a store overview page that displays about 20 products per page. The data for this page is sourced from a zipped (gzip) XML file (*.xml.gz). You can find the feed here: . Every day, I download this file to my server using PHP and ...

Error: Unable to use map function on users .. cannot perform mapping on functions

Initially, the map function in my code was working fine. However, suddenly an error started appearing when I included the users.map line. Surprisingly, if I comment out that line, the code works perfectly again. Even more strangely, if I uncomment it, ev ...

Link the index value of a v-for loop to the id of a newly created component

I need to create components in a loop within my Vue app, but I want each component to have a unique id value like "board-1" based on the index of the loop. Just like how I did it with v-bind:key="component-${block._uid}". How can I make this happen? < ...

The submission of FormData to the PHP server is causing an issue

I am having an issue with sending the formData to my PHP script using AJAX. Despite inspecting the elements, I can't find any errors in the process. Below is the structure of my form: The input values are sent to a JS file onclick event. <form c ...

I keep running into errors whenever I try to run npm install in my React JS project. The only way for me to successfully install dependencies is by using npm install --force. How can I go about resolving these

I am encountering this error message while working on my project: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @mui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="681b1c11040d1b ...

Problem with IE off-canvas scrolling

Currently, I am facing an issue with the scrolling functionality of an off-canvas sidebar on my Joomla 3 website. It seems to be working fine in Chrome and Firefox, but when it comes to Internet Explorer, the visible scroll bar refuses to move when attempt ...

Mastering data extraction from JSON using React JS (with Axios)

Being new to ReactJS and axios, I am facing a challenge. I need to iterate through JSON data and extract values where the key is a number (e.g. 0, 1, 2...). However, I am unsure how to implement this in my code since the server provides dynamic JSON data ...

Implementing custom fonts in Next.js using next-less for self-hosting

Seeking Solutions for Hosting Fonts in Next.js Application I am exploring the idea of self-hosting a font, specifically Noto, within my Next.js application that already utilizes the @zeit/next-less plugin. Should I rely on the npm package next-fonts to h ...

Verifying if any of the entries in a specific index contain a null value

Here is the structure I am working with: { "subs": [ { "status": "1", "run_settings": null, "ward": "/asda/asd/ada" "value": null, "name": null }, { "status": "0", "run_settings": null, "ward": ...

Tips for customizing fonts in react-pdf

I am having difficulty in changing fonts within react-pdf. // Register Font Font.register({ family: "Roboto", src: "https://cdnjs.cloudflare.com/ajax/libs/ink/3.1.10/fonts/Roboto/roboto-light-webfont.ttf" }); The default f ...

Checkbox malfunctioning when trying to add values after being checked

I have successfully completed a calculation system project using JavaScript. Everything works well, the calculations are accurate and taxes are included properly. However, I am facing an issue where the tax is not being included when I click on the checkbo ...