From Wikipedia, "Works of fan fiction are rarely commissioned or authorized by the original work's owner, creator, or publisher; also, they are almost never professionally published."
Whether it's published or not has nothing to do with whether it's a copyright or trademark violation. If I design and build a substantially similar household appliance to one that's under a patent, is that a patent violation? Yes, it is. Good luck enforcing it, though, and provided I'm not making money off it, the only amount the patent owner(s) or production rights holder(s) could legally recover is the net they'd have received had I purchased the device instead. So, for a vaccuum cleaner, what? $20? No one's going to sue for that. I could make my own chia pet and no one would sue for that, either.
Copyright and Trademark is very nearly the same, except that it's both broader and more murky. If I create a character named "Dirk Pitt" and publish it in a story online, the owner of the real Dirk Pitt, Clive Cussler (and counsel) will come after me even if I didn't make a penny. Will they win? Yeah, but as no profit was made, it'll be just the forced removal of the story I created and possibly a punitive fine.
The name Dirk Pitt falls under copyright law, but the teeth are weak for going after a purloined character, particularly if the setting is completely changed. "Dirk Pitt" is also trademarked, which has far larger teeth. Now you can't use it in any context without the express written permission of whoever holds the trademark.
Now - is it illegal to write such a story which copies characters and context? Not at all, provided you don't attempt to publish it, whether for free or pay. Star Trek fans are always writing books and scripts in the hopes they'll get picked up. Some do, most don't. Sending it in to the owners of that franchise is fine. Passing it around to a few friends for their edits/inputs is fine, too. Publishing it in any form beyond this scope is not fine and constitutes a copyright/trademark violation.