My guess is that you have some code that is modifying the Model.nodeDataArray without calling a Model method or setting that property.
By the way, goJsDiagram.nodes.count is a dramatically more efficient way to find out how many nodes there are, than building an Array and looking at its length.
So the problem was that the templateMap.add method was accidentally called during undo. After ensuring that the templateMap.add method is called only when intended it looks good.