There are real reasons why this happens. When you are asleep, or just really at ease, the brain is relaxed and the 'clutter' and stresses of daily life are greatly reduced. As a result, solutions to problems are much clearer and creativity has much more open space to play.
You can use it to your advantage when you really hit a wall with something. It's why taking a break to do something totally relaxing often results in new ideas and resolutions to problems.