Invalid position error when updating the state

Hello!
I’m getting started with CodeMirror and I’m having trouble dealing with an error I’m receiving when trying to update editor text. I’m implementing using Vue.js. To facilitate understanding, my goal is that whenever the addVarTest() function is called, an example code line should be added where the user’s cursor is positioned (or line 0 if none). To achieve this, I retrieve the current editor text as an array, then the line where the cursor is, I add this line to the text array at the desired position. Finally, I convert it back to text and try to update the state, but I receive the error:

Invalid position 83 in document of length 42
RangeError: Invalid position 83 in document of length 42’.

Below is my code:

addVarTest() {

            const viewState = this.view.viewState;

            // get the array of lines
            let textArr = viewState.state.doc.text;

            // get the global position of the cursor
            const cursor = viewState.state.selection.ranges[0].anchor;

            // get the cursor line
            const line = viewState.state.doc.lineAt(cursor);

            // add the new example line
            textArr.splice(line.number - 1, 0, 'const my_var = getVars("global", "my_var)');
            const newTxt = textArr.join('\n');

            this.code = newTxt;

            this.view.dispatch({
                changes: { from: 0, to: this.view.state.doc.length, insert: newTxt }
            });
        },

Followed by the CodeMirror initialization:

// initialization ...
createCode() {
            this.parent = this.$refs.codeParent;

            this.view = new EditorView({
                state: EditorState.create({
                    doc: this.code,
                    extensions: [
                        basicSetup,
                        javascript(),
                        keymap.of([indentWithTab, defaultKeymap]),
                        placeholder("Type your code here..."),
                        indentUnit.of("\t"),
                        tomorrow
                    ],
                    lineWrapping: true,
                }),
                parent: this.parent,
            });
        },