But what triggers it? I believe it's the brain's last attempt to "live" by thinking what it could've done to live (more). Sort of like when poisoned, jumping off a bridge, or just realizing your life is absolute shit.
It also doubles as an escape from the current desperate situation. Ignore the pain and dream.
Memory trips happen quite often with various drugs, too. Or when you're in such extreme pain (broken limbs, etc) your body releases a lot of endorphins which feels a lot like heroin.