Modeling connection remove issue

Hello everyone!
I am writing to ask you about an error I am having when deleting a Connection element. First, I have an event listener for “commandStack.connection.create.postExecute” and “commandStack.shape.create.postExecute” to delete elements that meet a specific condition right after they have been created. The method that eliminates the element itself is this:

eventBus.on([“commandStack.connection.create.postExecute”, “commandStack.shape.create.postExecute”], (event) => {
let id = method to get the id
if(condition) this.removeElement(id)

removeElement(id) {
let elementRegistry = this.bpmnModeler.get(‘elementRegistry’);
let modeling = this.bpmnModeler.get(‘modeling’);
let element = elementRegistry.get(id);
modeling.removeElements([ element ]);

The problem I have only happens with flow elements. For example, if the user adds a flow element to the canvas that achieves the condition to be deleted, after deleting that flow element, the error in this image appears:
Captura de pantalla 2023-12-13 a la(s) 18.59.28

Do you have any idea why is this happening and how to solve it?
Thank you!

Hello again. I could finally fix this issue by inserting a setTimeout like this:

    setTimeout(() => {
    }, 0);

I still don´t exactly understand why it worked using a setTimeout only in the case of Sequence Flows, but perhaps this solution will we useful for any other person facing a similar problem

You’d generally want to avoid executing commands within the context of an event listener as this breaks undo and redo. commandStack.connection.create.postExecute is an event you’d want to listen to only in very rare cases. I think what you are looking for is a command interceptor: bpmn-js Command Interceptor Starter - CodeSandbox

Can you describe in simple terms what kind of behavior you want to achieve?

Yes, in fact, the solution that I implemented was used within a class that extends CommandInterceptor. What I am trying to achieve is that if any canvas element exceeds a maximum value of a businessObject property (which always increments), that element should not appear or should be automatically removed from the canvas. I also tried to achieve this using a CustomRuleProvider, but since this option didn’t work either, I decided that the element would be inserted into the canvas and if the property exceeded the maximum value, it would be instantly deleted

An event you could listen to is elements.changed which is fired after command execution providing you with a list of all the elements that have changed. You could listen to that event to execute your custom logic.