prosemirror error - Applying a mismatched transaction

bug描述

使用 prosemirror 时,dispatch transcation 报错:

代码如下(简化版):

js 复制代码
import { inject } from "vue";
const editorView = inject("editorView");

function handleClick() {
  const view = editorView.value;
  view.dispatch(view.state.tr.deleteSelection());
}

在 prosemirror discuss 找到了相关问题:RangeError: Applying a mismatched transaction。pm 的作者在讨论中解释了这个 error 的含义:

"Mismatched transaction" errors mean that something is trying to dispatch a transaction that doesn't start from the view's current state---I.e. if you create the transaction but then don't synchronously dispatch it, it'd be possible for another transaction to happen in the meantime, which makes your transaction invalid. The rest of the stack trace for the error likely points at the code that's dispatching the transaction on the outdated (or, possibly, completely unrelated) state.

很奇怪,我没有用异步操作啊。顺着报错stack,找到 applyInner 方法。发现当 eq() 返回 false时,会抛出 error

查看 eq 方法,根据注释知道它是用来判断 this 和 other 是否代表同一块内容。

查看 this,是 Vue的 Reactive 对象,包着 doc Node。

查看 other:是 doc Node 对象

破案了。

解释

我项目用的 vue3。在父组件中把 editorView 用 ref 包了一下,然后 provide 下去。

js 复制代码
const editorView = ref()
provide("editorView", editorView );
onMounted(() => {
  editorView.value = new EditorView();
});

子组件(也就是调用 dispatch 的组件) inject 进来的是这个 ref 对象。
在 vue 3 中被 ref 包着的对象,通过.value 得到的不是原对象,而是原对象的 proxy!

vue2 vs vue3

js 复制代码
const obj ={a:1}
console.log(obj === ref(obj).value)

同样一段代码,在 vue2 环境中是 true,在 vue3 中是 false

平时工作项目里一直用 vue2,这次测试项目装的 vue3,没注意差别
一定要记得,vue2 和 vue3 的响应式原理是有区别的。平时开发不显眼,一旦踩坑就很麻烦

相关推荐
paopaokaka_luck7 小时前
宠物门店经营管理系统(销售与库存联动、进货自动记账、 退换与退款关联、员工个人业绩、ECharts 经营分析、滞销识别与客户分层、宠物档案年龄计算)
前端·javascript·spring boot·mysql·echarts·mybatis·1024程序员节
鶴哥只手遮天11 小时前
jQuery 4.0 源码架构与工程实践-第 10 章 尺寸、几何与显隐
前端·javascript·jquery
米米商聊13 小时前
图标能点,按钮就可用了吗?键盘、名称与收藏状态
前端·javascript
技术小甜甜14 小时前
【Cursor】Skill 被标黄色警告,怎么改成合格的 SKILL.md
开发语言·javascript·ai编程·cursor·1024程序员节·ai agent·skills
qetfw16 小时前
Bash 函数与流程控制:read、if、for、case 验证
linux·前端·javascript·bash
鬼手点金16 小时前
从 API 消息到模型 Token:Chat Template
java·前端·javascript·数据库·人工智能·深度学习·1024程序员节
Mr.Pascal18 小时前
Javascript之什么是作用域?
javascript·1024程序员节
microrain19 小时前
设备报文怎么变,SagooIoT 只约定三个函数名
javascript·物联网·golang·sagooiot
Bug收容所19 小时前
Vue+JS Day3
前端·javascript·vue.js·前端框架·1024程序员节
小羊没烦恼!20 小时前
.NET无侵入自动化探针原理和主流实现
运维·开发语言·javascript·python·自动化·.net·1024程序员节