首页 > 解决方案 > 对 javascript 对象的引用显然在不同的地方返回不同的值,中间没有修改

问题描述

我在一个函数中使用了两次变量,但即使我没有对其进行任何修改,它也会返回不同的值。

这发生在使用 Vue.js (v2) 开发的表单组件中,该组件调度 Vuex 操作。我认为这与 Vue/Vuex 本身无关,但理解部分代码很重要。

这是我的组件中的相关代码

import { mapActions } from 'vuex'

export default {

  data() {
    return {
      product: {
        code: '',
        description: '',
        type: '',
        productImage: [], 
        productDocs: {},
      }
    }
  },

  methods: {

    ...mapActions(['event']),

    save() {
      console.log("this.product:", this.product)
      const valid = this.$refs.form.validate() // this validates the form
      console.log("this.product:", this.product)
      if (valid) {
        try {
          this.event({
            action: 'product/addProduct',
            data: this.product
          })
        }
        finally {
          this.close()  
        }
      }
    },

// other stuff

以及 vuex 动作“事件”的一小段代码

event: async ({ dispatch }, event) => {
      const time = new Date()
      const evid = `${Date.now()}|${Math.floor(Math.random()*1000)}`
      console.log(`Preparing to dispatch... Action: ${event.action} | data: ${JSON.stringify(event.data)} | Event ID: ${evid}`)

      // enriching event
      event.evid = evid;
      event.timestamp = time;
      event.synced = 0

      // Push user event to buffer
      try {
        await buffer.events.add(event)

      } catch (e) {
        console.log(`Error writing event into buffer. Action ${event.action} | evid: ${evid} `)
      }

      // dispatch action 
      try {
        await dispatch(event.action, event)
      }
      catch (err) {
        console.log(`Error dispatching action: ${event.action} | data: ${event.data}\n${err.stack || err}`)
        window.alert('Could not save. Try again. \n' + err + `\n Action: ${event.action} | data: ${event.data}`)
      }
    },

问题出在this.product. 我已经放置了几个console.log来检查实际值,因为它没有按预期工作。来自函数的日志save()return undefined,但在event函数(一个 vuex 操作)中,值符合预期,如控制台日志中所示:

当我登录this.productsave()功能时。两个日志是一样的。 控制台.log(this.product)

当我登录eventvuex 操作时,它显示这event.data实际上是产品。 <code>event</code> 函数中的 console.log

我必须在这里做一些非常错误的事情,但我对此完全视而不见。任何帮助表示赞赏。

标签: javascriptvue.jsvuex

解决方案


@Sumurai8:感谢您编辑问题和提示。

部分原因可能是打开的产品旁边的那个小 i 。如果你将鼠标悬停在它上面,它会说“对象刚刚被评估过”,这意味着它会在你打开对象时评估对象中的内容,这是在执行操作之后的方式。[...] 无论是什么改变了产品,都可能在某处事件发生后发生。

它实际上帮助我找到了解决方案。

基本上在this.close函数finally语句中调用的save()函数中,我正在重置表单,因此this.product,它仅用于保存表单数据。因此,在评估时,对象具有未定义的属性,而event函数在重置之前设法输出到控制台。但是最后存储不会按预期更新(这就是我注意到问题的方式),因为其中调用的event函数和操作是异步的,因此值在 vuex 存储的实际突变之前被重置。

JSON.stringify(this.product)即使在方法内,日志记录也会输出正确的值save()。我用它来创建更健壮的数据副本并将其传递给事件函数,如下所示:

this.event({
  action: 'product/addProduct',
  data: JSON.parse(JSON.stringify(this.product))
})

现在一切都像魅力一样。


推荐阅读