Error in Vuex when attempting to modify a local version of the state leads to a mutation issue

I'm facing a perplexing issue in my Vue application that has left me puzzled. The error message I'm encountering when trying to update a local version of a state element reads as follows:

Error: [vuex] Do not mutate vuex store state outside mutation handlers.

Below is a snippet of the code causing this issue:

import { mapGetters } from 'vuex'
export default {
    name: 'sampleComponent',
    data() {
        return {
            userModel: null
        }
    },
    mounted() {
        this.userModel = this.user
    },
    computed: {
        ...mapGetters(['getApplicationUsers']),
        user() {
            return JSON.parse(JSON.stringify(this.getApplicationUsers[0]))
        }
    },
    methods: {
        addUserRole() {
            if (!this.userModel.userRoles.includes("newRole")) {
                this.userModel.userRoles.push("newRole")
            }
        }
        removeUserRole() {
            let index = this.userModel.userRoles.indexOf("newRole");
            if (index > -1) {
                this.userModel.userRoles.splice(index, 1)
            }
        }
}

Whenever the removeUserRole function is invoked, the mutation error occurs. Adding roles with addUserRole works smoothly, but removing a role triggers the error message.

Could someone shed some light on this behavior for me? Shouldn't userModel be independent from the state and mutable after being deep copied?

Answer №1

Your code has a few issues that need to be addressed...

  1. It is recommended to define the data function in a component
  2. Make sure to initialize all component properties in the data function to ensure reactivity
  3. If you need to create a local copy of a state property, do it within the data function

Considering the suggestions above, you can try this revised code snippet

data () {
  return {
    objectModel: {...this.$store.getters.getApplicationUsers[0]}
  }
}

Answer №2

After reading Decade Moon's initial comment, I was able to find the solution to my problem. I successfully managed to create a mutable object using JSON.parse/JSON.stringify. However, I encountered an issue when I tried to mutate the object in my local code because there was a reference to it in the store where I had temporarily stored it.

The reason I didn't face an error initially was because I hadn't committed the userModel to the store at that point. It was only when I later committed userModel to the store that the errors started occurring.

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 fixed position setting does not anchor the elements to the bottom of a container

When applying the following styles: #fullpage-menu > .gradient { position: fixed; bottom: 0; left: 0; width: 100%; height: 0.3rem; } To the element with ID #fullpage-menu, which is styled as follows: #fullpage-menu { height: 100 ...

How can one effectively manage irregularly nested object/arrays within a Meteor framework?

Having difficulty finding a smart and effective method to manage nested arrays/objects with varying dimensions in nodeJS. These irregular arrays/objects can have 1, 2, 3, or more dimensions. For instance, consider these 2 different scenarios : Scenario 1 ...

The Google map is failing to load on the webpage

My id="ieatmaps" is set up to call the googlemaps.js, but for some reason, it's not displaying correctly. I must be missing something. function initMap() { var map = new google.maps.Map(document.getElementById('ieatmaps'), { c ...

Exploring the Ins and Outs of Debugging JavaScript in Visual Studio Using

I encountered a peculiar issue while testing some code. When the program is executed without any breakpoints, it runs smoothly. However, if I introduce a breakpoint, it halts at a certain point in the JSON data and does not allow me to single-step through ...

How to Stop AJAX Requests Mid-Flight with JQuery's .ajax?

Similar Question: Stopping Ajax Requests in JavaScript with jQuery Below is the straightforward piece of code that I am currently using: $("#friend_search").keyup(function() { if($(this).val().length > 0) { obtainFriendlist($(this).va ...

Updating the state of an object within a mapping function

I've been struggling with this issue for two days now. Despite my efforts to find a solution online, I am still stuck and starting to believe that I might be missing something. The main functionality of the app is to click a button and watch an apple ...

Utilizing Piwik Analytics in jQuery Mobile Framework

Having an issue with tracking users on my mobile Web App using Piwik. Due to AJAX, only views on the first page are being tracked. I attempted to use the pageinit function to load the Piwik tracking script on every page, but it still only tracks the firs ...

What are the reasons for the success function not being called and what steps can be taken to correct it

Whenever I attempt to submit the post, the data is successfully sent and received by the server, but the success function never gets called. In the network inspector tab of Chrome, the connection shows as stalled with a warning: "connection is not finished ...

The addition of meshes in real-time leads to a decrease in control responsiveness

I'm currently working on creating a 3D map using Three.js. My process involves building the geometry and texture with images of size 256x256 pixels, then constructing a THREE.Mesh to add to the scene upon completion. However, I've noticed that ...

Hydrate a SSR VUE application to some extent

We are currently working on a website that unfortunately features numerous advertisements. Our plan is to utilize VUE for building the site, implement server side rendering, and then hydrate it on the client side. The issue lies in the fact that these adv ...

Error: Angular is encountering an issue with accessing the property 'push' as it is currently undefined

I have successfully created a news ticker that works well in my codepen example. However, I am encountering an issue with integrating it into my code structure. The error message I am currently receiving is: Cannot read property 'push' of undefi ...

What could be causing my webpage to automatically refresh following a POST request in NodeJS?

Utilizing the express framework alongside NodeJS, I have encountered an issue where my client webpage refreshes after making a POST request that triggers a python script and returns a JSON object to the client. My dilemma lies in preventing this automatic ...

I created a custom discord.js-commando command to announce all the channels that my bot is currently active in, however, encountered an unexpected error

const Commando = require('discord.js-commando'); module.exports = class AnnounceCommand extends Commando.Command { constructor(client) { super(client, { name: 'announce', aliases: ['an'], ...

Tips for efficiently utilizing both client-server side rendering and static generation rendering in web development

I am looking to implement static generation for top products using getStaticProps. Currently, there are sections in my rendering that do not require static generation, such as comments and related products. Here is the full code snippet: export default fu ...

What is the best way to maintain the correct 'this' context for a function that is outside of the Vue

I'm struggling with my Vue component and encountering some errors. <script lang="ts"> import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, va ...

using a dynamic v-model as an argument in a function call

I am completely new to using vuejs and currently working on creating a dynamic table. In this table, the left column will contain hidden input fields that will be used to query a database and display the results in a pop-up window for quick referencing. ...

Using both Promise based architecture and events in Node.js can lead to unexpected behavior and should be avoided

Currently, I am developing a nodejs application that is expected to grow in size. Despite my efforts, I have not been able to find many resources on advanced Nodejs project architecture and structure. I am wondering if it would be considered bad practice ...

Loop through the items using the V-for directive and access each item in the computed property

Check out my code snippet: <div v-for="list in getList" :key="list.id" class="tab"> <h3>{{day(list)}}</h3> <div class="details"> <img :src="require('../assets/day.svg')" alt="icon"> ...

The server at localhost responds with a CANNOT GET/ error message

This is the code snippet I've been working on: const express = require('express'); const app = express(); const bodyparser = require('body-parser'); app.use(bodyparser.urlencoded({extended: false})); app.use(bodyparser.json()); c ...

A ServiceWorker used a promise in FetchEvent.respondWith() that resulted in a non-Response value of 'undefined'. This caused an issue in browser-sync

There are times when my server encounters an error in the console: Failed to load ‘http://localhost:3000/browser-sync/socket.io/?EIO=3&transport=polling&t=Lm2wn4p’. A ServiceWorker passed a promise to FetchEvent.respondWith() that reso ...