Here's my hypothesis for why this bug occurs. Through researching this bug and in my own experience, it seems to happen on sub-vessels (a vessel docked to a conglomeration of vessels that doesn't show up as a unique vessel in the save file, but is named and indicated under the docking modules "DOCKEDVESSEL" vesselname = ...) that don't have any sort of control pod (manned or unmanned) as part of their vessel (there may be one on another sub-vessel somewhere in the rest of the mother-vessel, but not on the sub-vessel that doesn't get its docking port's state = Docked (dockee) set correctly).
So I don't know why it happens but I found out how to fix the undock bug from someone's suggestion in another thread (I forget where I saw it). Since Scott Manley recently encountered this bug in his most recent reusable space program, I thought I'd be a constructive member of the community and post my solution. Excuse me for my lack of proper annotations/formatting, this is probably the first time I've ever really posted in a forum. Maybe the mods can format it properly once I post it? Hope this helps out! It's also a selfish move because I want to see Scott Manley continue his trip to Moho!