My most educated guess is that if you died while having a nightmare, you'd initially leave your body with the "echo" of that nightmare still lingering in your consciousness, until it fades. It's kind of like how when you first wake up from a really vivid dream or nightmare, it takes a while for the memory to fade a little bit as you rejoin waking reality. This "fading" effect can be observed while on certain psychedelics, just like how anything you focus on can become a whole world you get stuck in while tripping.
This reason why I think this about death is because OBEs and astral projection work similarly. There are many techniques that use dreams as the gateway to leave the body, but first you have to recognize that it's a dream before you can develop the skill to do that. Initially you're in the vivid dream, and then you realize you can leave. When you're just starting to learn how to do this, your OBE is initially a mix of real world imagery (i.e. seeing your bedroom), but there may be dream images overlaid, making it a mix of two worlds because consciousness is clinging to the dream image. Dreams are internal projections, whereas OBEs are external projections. There's really no difference between the inner and the outer, you can project consciousness into both. But when you haven't mastered the OBE version, part of your mind will still cling to the internal dream state because it's more familiar and automatic.
Although it's not possible to know for sure, my strong suspicion is that when we die, our entire lifetime of memories is similar to this, including how we died. If someone dies traumatically then probably for the first little while outside of the body they still believe that it's happening, even though the situation has passed. Then they gradually wake up to their non-corporeal existence again, and remember who they are.