It happens to grown men. It happens to little boys. Even babies. Nocturnal penile tumescence (NPT), known these days as “morning wood,” is a universal human male trait. In fact, our very, very little bros get ‘em in utero. And it’s not just morning wood, it’s midnight wood and 3 a.m. wood, too.
That provides a clue as to why men have erections when we’re sleeping. NPT is very closely linked to rapid eye movement (REM) sleep. The exact mechanism at work has not yet been fully teased out, but during REM sleep activity in part of the brain called the pontine area (among others) increases. It’s thought that this triggers a cascade of events including the release of nitric oxide by nerve fibers in the penis. This cascade is mediated by androgen hormones like testosterone.
Though it happens in REM sleep, which is also associated with dreams, we don’t necessarily have to be dreaming about all the ways guys who go to Vegas have more fun than we do when we go to Vegas. After all, those in utero boys haven’t yet heard of the "gentlemen's club" the Spearmint Rhino. NPT does not depend on erotic visuals.
A 2005 article in the Journal of Sexual Medicine suggests that NPT serves an evolutionary purpose: “It has been speculated that the main function of nocturnal erections is to provide adequate engorgement of the corpora cavernosa, which then leads to increased tissue oxygenation. This is in turn [prevents] cavernous fibrosis, the histopathological basis for corporeal veno-occlusive dysfunction, which probably is the most common cause of organic erectile dysfunction.”
In other words, our brains are giving our penises a little nighttime workout, strictly for maintenance, to make sure we stay tuned up. Nothing to worry about.